PatternsGraph Traversal Pattern

Graph Traversal Pattern

Master the exploration of graphs using BFS and DFS — essential for problems involving connected components, cycles, shortest paths, and maze-like challenges.

1 Problems
6-8 Hours
Easy to Hard

When to Use Graph Traversal Pattern

Connected Components

To explore all nodes in a component or check if nodes are connected

Cycle Detection

To detect cycles in directed or undirected graphs

Shortest Path

To compute shortest path in unweighted graphs (BFS) or weighted graphs (Dijkstra)

Maze and Grid Problems

When navigating through 2D/3D grids with obstacles or directions

Key Insights & Tips

BFS = Shortest Path (Unweighted)

Use BFS to find the shortest path in unweighted graphs

DFS = Depth Exploration

DFS is great for deep search, cycle detection, and topological sort

Avoid Re-visiting

Always maintain a visited set/map to prevent infinite loops

Adjacency List vs Matrix

Adjacency list is space-efficient for sparse graphs, matrix for dense graphs

Code Examples

DFS (Adjacency List)

Recursive depth-first traversal using visited set

Time: O(V + E)Space: O(V)
function dfs(graph: Map<number, number[]>, node: number, visited: Set<number>) {
    if (visited.has(node)) return;
    visited.add(node);
    console.log(node); // or push to result
    
    for (const neighbor of graph.get(node) || []) {
        dfs(graph, neighbor, visited);
    }
}

// Usage:
const graph = new Map([[0, [1, 2]], [1, [0, 3]], [2, [0]], [3, [1]]]);
dfs(graph, 0, new Set());

BFS (Adjacency List)

Breadth-first traversal using queue and visited set

Time: O(V + E)Space: O(V)
function bfs(graph: Map<number, number[]>, start: number) {
    const visited = new Set<number>();
    const queue: number[] = [start];
    visited.add(start);

    while (queue.length > 0) {
        const node = queue.shift()!;
        console.log(node); // or push to result

        for (const neighbor of graph.get(node) || []) {
            if (!visited.has(neighbor)) {
                visited.add(neighbor);
                queue.push(neighbor);
            }
        }
    }
}

Graph as Matrix (DFS)

DFS on a grid for maze problems

Time: O(m * n)Space: O(m * n)
function dfsGrid(grid: number[][], i: number, j: number, visited: boolean[][]) {
    const rows = grid.length, cols = grid[0].length;
    if (i < 0 || i >= rows || j < 0 || j >= cols || grid[i][j] === 0 || visited[i][j]) return;
    
    visited[i][j] = true;

    const dirs = [[0,1], [1,0], [0,-1], [-1,0]];
    for (const [dx, dy] of dirs) {
        dfsGrid(grid, i + dx, j + dy, visited);
    }
}

Your Progress

Problems Solved3/20
15% Complete17 remaining

Practice Problems

View All

Clone Graph

medium

Asked by Companies

GoogleAmazonFacebookUberMicrosoftBloomberg

Next Pattern

Ready for the next challenge?

Backtracking