Traversal Techniques

Pattern: BFS and DFS

medium

Build the adjacency list, then traverse from vertex 0 twice: breadth-first with a queue (nearest vertices first) and depth-first with recursion (as deep as possible first). Neighbours are tried in the order the edges were given.

The problem

Given n vertices and undirected edges, return [bfs, dfs]: the breadth-first and depth-first orders from vertex 0. Vertices are numbered from 0 and each edge is given as [u, v].

Think first

  • Which structure gives nearest-first order?
  • Which gives deepest-first order?
  • How do both avoid visiting a vertex twice?

Hints

    Brute force, and why it fails

    There is no slower version worth writing; the point is the two orders.

    The key insight

    BFS and DFS are the same loop with a queue or a stack; the order they visit vertices is all that differs.

    Dry run

    n = 5, edges [0, 1], [0, 2], [0, 3], [2, 4]. Adjacency: 0: 1 2 3; 2: 0 4.

    Step 1 of 3

    The plan

    bfs: queue = [0]; while queue: u = pop front; add unvisited neighbours
    dfs(u): mark u; for v in adj[u]: if unvisited: dfs(v)
    

    Complexity

    Time
    O(V + E)
    Space
    O(V + E)

    Each vertex and edge is handled once per traversal.

    Edge cases

    • A single vertex with no edges.
    • A graph in several pieces.
    • Many edges at one vertex.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<List<Integer>> bfsAndDfs(int n, int[][] edges) {
            List<List<Integer>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
            for (int[] e : edges) { adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
            List<Integer> bfs = new ArrayList<>(), dfs = new ArrayList<>();
            boolean[] seen = new boolean[n];
            Queue<Integer> q = new ArrayDeque<>();
            q.add(0);
            seen[0] = true;
            while (!q.isEmpty()) {                  // breadth first: nearest vertices first
                int u = q.poll();
                bfs.add(u);
                for (int v : adj.get(u)) if (!seen[v]) { seen[v] = true; q.add(v); }
            }
            dfs(0, adj, new boolean[n], dfs);       // depth first: go as deep as possible first
            return Arrays.asList(bfs, dfs);
        }
    
        private void dfs(int u, List<List<Integer>> adj, boolean[] seen, List<Integer> out) {
            seen[u] = true;
            out.add(u);
            for (int v : adj.get(u)) if (!seen[v]) dfs(v, adj, seen, out);
        }
    }

    C++

    class Solution {
    public:
        vector<vector<int>> bfsAndDfs(int n, vector<vector<int>>& edges) {
            vector<vector<int>> adj(n);
            for (const vector<int>& e : edges) { adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); }
            vector<int> bfs, dfsOut;
            vector<bool> seen(n, false);
            queue<int> q;
            q.push(0);
            seen[0] = true;
            while (!q.empty()) {                    // breadth first: nearest vertices first
                int u = q.front();
                q.pop();
                bfs.push_back(u);
                for (int v : adj[u]) if (!seen[v]) { seen[v] = true; q.push(v); }
            }
            vector<bool> seen2(n, false);
            dfs(0, adj, seen2, dfsOut);             // depth first: go as deep as possible first
            return vector<vector<int>>{bfs, dfsOut};
        }
    
        void dfs(int u, vector<vector<int>>& adj, vector<bool>& seen, vector<int>& out) {
            seen[u] = true;
            out.push_back(u);
            for (int v : adj[u]) if (!seen[v]) dfs(v, adj, seen, out);
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def bfsAndDfs(self, n: int, edges: list[list[int]]) -> list[list[int]]:
            adj = [[] for _ in range(n)]
            for u, v in edges:
                adj[u].append(v)
                adj[v].append(u)
            bfs, seen, q = [], {0}, deque([0])
            while q:                                # breadth first: nearest vertices first
                u = q.popleft()
                bfs.append(u)
                for v in adj[u]:
                    if v not in seen:
                        seen.add(v)
                        q.append(v)
            dfs, seen2 = [], set()
    
            def go(u):                              # depth first: go as deep as possible first
                seen2.add(u)
                dfs.append(u)
                for v in adj[u]:
                    if v not in seen2:
                        go(v)
    
            go(0)
            return [bfs, dfs]

    Common mistakes

    • Marking vertices when they leave the queue, so they are queued twice.
    • Visiting neighbours in a different order from the input.

    Similar problems