Graph Traversal (BFS & DFS)

Breadth-first and depth-first search — the two ways to explore any graph, and the dozens of problems they solve.

Intermediate 2 min readLesson 11 of 18 Interview Q&A

Almost every graph algorithm is built on one of two traversals. Both visit every reachable vertex and edge once: O(V + E).

Breadth-first search (BFS)
  • Uses a queue (FIFO)
  • Explores in layers by distance from the source
  • Finds shortest paths in unweighted graphs
  • Memory: O(width of the frontier)
Depth-first search (DFS)
  • Uses a stack or recursion (LIFO)
  • Goes as deep as possible, then backtracks
  • Cycle detection, topological sort, components, path existence
  • Memory: O(depth)

Step through both on the same graph:

InteractiveBreadth-first search
ABCDEFGH
queue (front → back)
A
visited order
A
currentin queuevisited / final
Enqueue start A, mark visited
1/17

BFS

Mark a vertex visited when you enqueue it, not when you dequeue it — otherwise the same vertex can be enqueued many times.

// Shortest distance (in edges) from src to every vertex
int[] bfs(List<List<Integer>> adj, int src) {
    int[] dist = new int[adj.size()];
    Arrays.fill(dist, -1);
    Deque<Integer> q = new ArrayDeque<>();
    dist[src] = 0;
    q.offer(src);
    while (!q.isEmpty()) {
        int u = q.poll();
        for (int v : adj.get(u)) {
            if (dist[v] == -1) {           // unvisited
                dist[v] = dist[u] + 1;     // mark on enqueue
                q.offer(v);
            }
        }
    }
    return dist;
}

BFS on a grid

Grids are implicit graphs: each cell's neighbours are the 4 (or 8) adjacent cells. Use a direction array.

Shortest path in a binary maze
int shortestPath(int[][] grid) {              // 0 = open, 1 = wall
    int R = grid.length, C = grid[0].length;
    int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
    int[][] dist = new int[R][C];
    for (int[] row : dist) Arrays.fill(row, -1);
    Deque<int[]> q = new ArrayDeque<>();
    q.offer(new int[]{0, 0});
    dist[0][0] = 0;
    while (!q.isEmpty()) {
        int[] p = q.poll();
        if (p[0] == R - 1 && p[1] == C - 1) return dist[p[0]][p[1]];
        for (int[] d : dirs) {
            int r = p[0] + d[0], c = p[1] + d[1];
            if (r >= 0 && r < R && c >= 0 && c < C && grid[r][c] == 0 && dist[r][c] == -1) {
                dist[r][c] = dist[p[0]][p[1]] + 1;
                q.offer(new int[]{r, c});
            }
        }
    }
    return -1;
}

Multi-source BFS: start with all sources in the queue at distance 0 — "rotting oranges", "distance to nearest 0", "walls and gates". 0-1 BFS: edges weigh 0 or 1 → use a deque, push 0-edges to the front.

DFS

// Count connected components
int countComponents(int n, List<List<Integer>> adj) {
    boolean[] seen = new boolean[n];
    int comps = 0;
    for (int s = 0; s < n; s++) {
        if (seen[s]) continue;
        comps++;
        dfs(s, adj, seen);
    }
    return comps;
}
void dfs(int u, List<List<Integer>> adj, boolean[] seen) {
    seen[u] = true;
    for (int v : adj.get(u)) if (!seen[v]) dfs(v, adj, seen);
}

Cycle detection in a directed graph (three colours)

White = unvisited, grey = on the current recursion path, black = finished. An edge to a grey vertex is a back edge → cycle.

boolean hasCycle(List<List<Integer>> adj) {
    int[] color = new int[adj.size()];              // 0 white, 1 grey, 2 black
    for (int u = 0; u < adj.size(); u++)
        if (color[u] == 0 && dfsCycle(u, adj, color)) return true;
    return false;
}
boolean dfsCycle(int u, List<List<Integer>> adj, int[] color) {
    color[u] = 1;
    for (int v : adj.get(u)) {
        if (color[v] == 1) return true;              // back edge
        if (color[v] == 0 && dfsCycle(v, adj, color)) return true;
    }
    color[u] = 2;
    return false;
}

What each traversal is for

TaskUse
Shortest path, unweightedBFS
Level-by-level processingBFS
Connected components / flood fillEither (DFS is shortest to write)
Cycle detection (directed)DFS with colours
Topological orderDFS post-order or Kahn's BFS
Bipartite checkBFS/DFS 2-colouring
Bridges / articulation pointsDFS with discovery times (Tarjan)
Strongly connected componentsDFS (Kosaraju / Tarjan)
Key takeaways
  • BFS = queue = layers = unweighted shortest paths.
  • DFS = stack/recursion = deep first = cycles, ordering, components.
  • Both are O(V + E); always track visited vertices.
  • Grids and state spaces are implicit graphs — generate neighbours on the fly.
Interview questions
QWord ladder: shortest transformation from beginWord to endWord changing one letter at a time.hard

BFS over words. Neighbours of a word: change each position to a–z and keep results in the dictionary set (remove them when enqueued). O(N · L · 26). Bidirectional BFS from both ends roughly square-roots the explored frontier.

QClone a graph.medium

BFS/DFS with a map from original node to its clone. On visiting a neighbour, create its clone if missing and add it to the current clone's neighbour list. The map doubles as the visited set.

QWhy is DFS not suitable for shortest paths?easy

DFS may reach a vertex first via a long path; nothing guarantees the first visit is the shortest. BFS processes vertices in nondecreasing distance order, so the first visit is optimal (for unweighted edges).