Algorithms Playbook
PatternTime O(V + E) · Space O(V)10 min read

Graphs: BFS and DFS

How to model a problem as a graph, the two ways to explore one, and the grid problems (islands, shortest path in a maze) that are secretly graphs.

In short

A graph is nodes and edges. BFS uses a queue and explores in rings: the first time it reaches a node is via a shortest path (unweighted). DFS uses a stack (or recursion) and dives deep. Both cost O(V + E). Always keep a visited set, or cycles will loop forever.

Modelling and representing a graph

Whenever something is connected to something else (cities and roads, people and friends, courses and prerequisites, cells in a grid), think graph. The usual representation is an adjacency list: for each node, the list of its neighbours.

RepresentationSpaceCheck an edgeList neighbours
Adjacency listO(V + E)O(degree)O(degree)
Adjacency matrixO(V²)O(1)O(V)

Same graph, two orders

Switch between BFS and DFS and compare the visit order. The only change in the code is which end of the container you take from.

Graph traversal from node A
Algorithm
Speed

queue (leaves from the left)

0A

visit order

0·
ABCDEFG
1def bfs(graph, start):
2 seen = {start}
3 queue = deque([start])
4 while queue:
5 node = queue.popleft()
6 for nb in graph[node]:
7 if nb not in seen:
8 seen.add(nb)
9 queue.append(nb)
BFS explores in rings around the start: all nodes 1 step away, then 2 steps, and so on. A queue gives that order.

Variables

startA
Step 1/16· Pops: 0
Both visit each node and edge once: O(V + E). BFS finds the shortest path in an unweighted graph; DFS is the natural fit for exploring, cycles and connected components.

Which one to use

BFS

  • Shortest path in an unweighted graph or grid
  • Minimum number of steps / moves / mutations
  • Level by level, multi-source (start from all sources at once)
  • Memory: the widest ring

DFS

  • Does a path exist? Connected components, flood fill
  • Detect cycles, topological order
  • Backtracking and exploring all possibilities
  • Memory: the deepest path (recursion depth)
def num_islands(grid):
    def sink(r, c):
        if not (0 <= r < len(grid) and 0 <= c < len(grid[0])) or grid[r][c] != '1':
            return
        grid[r][c] = '0'                      # mark visited
        for dr, dc in ((1,0),(-1,0),(0,1),(0,-1)):
            sink(r + dr, c + dc)
    count = 0
    for r in range(len(grid)):
        for c in range(len(grid[0])):
            if grid[r][c] == '1':
                count += 1; sink(r, c)
    return count

Key takeaways

  • 01Model it as a graph: nodes, edges, adjacency list.
  • 02BFS (queue) gives shortest paths in unweighted graphs; DFS (stack) explores and detects.
  • 03Both are O(V + E) and need a visited set.
  • 04A grid is a graph where each cell has up to four neighbours.

Check your understanding

1 of 3

Which finds the shortest path in an unweighted graph?

Related topics