Pattern #49
Graph BFS
Important interview questions, thinking patterns, Level Wave Expansion, Enqueue Visited rule, Parent Map Path Reconstruction, Multi-Source BFS, and Go templates.
Must Solve
20 core questions — solve these first.
- 1.Shortest Path in Binary Matrix8-directional BFS in binary grid from (0,0) to (n-1, n-1) with distance ring incrementmedium
- 2.Rotting OrangesMulti-Source BFS: enqueue all initial rotten oranges at minute 0 and spread rot in parallel wavesmedium
- 3.Word LadderImplicit Graph BFS: transform 1 character at a time checking dictionary set; Bidirectional BFS optimizes search spacehard
- 4.Open the LockImplicit State BFS: 8 wheel-turn neighbor combinations starting from "0000" avoiding deadendsmedium
- 5.Number of IslandsGrid BFS: start BFS on unvisited "1"s and mark connected land mass to "0"medium
- 6.Number of ProvincesAdjacency Matrix BFS: loop over all nodes; if unvisited, run BFS to mark componentmedium
- 7.Clone GraphQueue BFS + HashMap mapping original node -> copied node to prevent cycle duplicatesmedium
- 8.Flood Fill4-directional Grid BFS changing matching initial color cells to new coloreasy
- 9.01 MatrixMulti-Source BFS: enqueue all zero cells at distance 0 and expand outward to calculate distance to nearest 0medium
- 10.Walls and GatesMulti-Source BFS: enqueue all gates (0) at once and update room distances in expanding ringsmedium
- 11.Minimum Genetic MutationBFS gene string mutation in bank set with 1-character difference edgesmedium
- 12.Keys and RoomsBFS reachability starting from room 0 enqueuing newly unlocked room keysmedium
- 13.Snakes and LaddersBoard BFS converting 1D board index to 2D matrix coordinates + dice roll moves (1..6)medium
- 14.As Far from Land as PossibleMulti-Source BFS starting from all land cells (1) outward into water cells (0)medium
- 15.Shortest Bridge1. DFS to find & mark first island -> 2. Multi-Source BFS from first island cells to reach second islandmedium
- 16.Minimum Knight Moves8-directional knight move offsets BFS from (0,0) to target (x,y) with quadrant symmetrymedium
- 17.Bus RoutesBipartite Route/Stop Graph BFS: queue bus routes and track visited routes & stopshard
- 18.Jump Game IIIBFS from start index moving to i + arr[i] and i - arr[i] checking for value 0medium
- 19.Nearest Exit from Entrance in MazeGrid BFS level rings starting from entrance to reach boundary empty cellmedium
- 20.Detonate the Maximum BombsRun BFS from each bomb as source; directed edge exists if dist(u,v) <= radius(u)medium
Also Important
8 more questions worth practicing.
- 21.Perfect SquaresState BFS: starting at n, subtract perfect squares (1, 4, 9...) level-by-level until 0medium
- 22.Word Ladder IIBFS to build parent predecessor DAG + DFS Backtracking to construct all shortest pathshard
- 23.All Nodes Distance K in Binary TreeConvert Binary Tree to Undirected Graph (adding parent pointers) + BFS distance Kmedium
- 24.Shortest Path Visiting All NodesBitmask BFS: queue tuple (currNode, visitedBitmask) with 2^N state spacehard
- 25.Minimum Operations to Convert NumberImplicit State BFS: apply +, -, ^ operations on current x to reach goalmedium
- 26.Shortest Path with Alternating ColorsBFS with tuple state (node, edgeColor) expanding via red/blue alternating edgesmedium
- 27.Minimum Jumps to Reach HomeBFS with state (position, jumpedBackwardsBool) obeying backward jump constraintsmedium
- 28.Minimum Number of Flips to Convert Binary Matrix to Zero MatrixBitmask State BFS flipping 3x3 binary matrix cells to zero statehard
How to Think
- Need shortest path with equal-cost edges?BFS (Level-by-level distance rings)
- Need minimum number of moves / steps?BFS
- Many starting points spread together?Multi-Source BFS
- Need nearest node/state?BFS
- Graph has cycles?BFS + Visited Set (Mark when ENQUEUED!)
Go Graph BFS Code Templates
Level-by-Level Distance BFS & Multi-Source BFS in Go
// 1. Level-by-Level Distance BFS (Equal-Cost Shortest Path)
func shortestPathBFS(n int, graph [][]int, start, target int) int {
queue := []int{start}
head := 0 // Head pointer avoids O(N) slice reallocation!
visited := make([]bool, n)
visited[start] = true // Mark WHEN ENQUEUED!
distance := 0
for head < len(queue) {
levelSize := len(queue) - head
for i := 0; i < levelSize; i++ {
curr := queue[head]
head++
if curr == target {
return distance
}
for _, next := range graph[curr] {
if !visited[next] {
visited[next] = true // Mark WHEN ENQUEUED!
queue = append(queue, next)
}
}
}
distance++
}
return -1
}
// 2. Multi-Source BFS (Rotting Oranges)
func orangesRotting(grid [][]int) int {
rows, cols := len(grid), len(grid[0])
queue := [][2]int{}
freshCount := 0
// Enqueue ALL initial sources at minute 0!
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
if grid[r][c] == 2 {
queue = append(queue, [2]int{r, c})
} else if grid[r][c] == 1 {
freshCount++
}
}
}
if freshCount == 0 { return 0 }
minutes := 0
dirs := [][2]int{{-1,0}, {1,0}, {0,-1}, {0,1}}
for len(queue) > 0 {
size := len(queue)
spread := false
for i := 0; i < size; i++ {
curr := queue[0]
queue = queue[1:]
r, c := curr[0], curr[1]
for _, d := range dirs {
nr, nc := r+d[0], c+d[1]
if nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1 {
grid[nr][nc] = 2 // Mark rotten WHEN ENQUEUED!
freshCount--
spread = true
queue = append(queue, [2]int{nr, nc})
}
}
}
if spread { minutes++ }
}
if freshCount > 0 { return -1 }
return minutes
}👉 Total Time: O(V + E) / O(R · C) | Space: O(V) / O(R · C)
Mandatory BFS Rule: Mark Visited When ENQUEUED
1. The Golden Enqueue Rule: In Graph BFS, ALWAYS mark visited[neighbor] = true as soon as you append the node to the queue!
2. Why? If node D is connected to both B and C, waiting to mark D as visited until it is popped allows both B and C to enqueue D, causing duplicate queue entries and exponential memory explosion.
Multi-Source BFS & Path Reconstruction
1. Multi-Source BFS: When multiple starting points expand simultaneously (Rotting Oranges, 01 Matrix, Walls and Gates), push ALL initial sources into the queue before starting the BFS loop!
2. Shortest Path Reconstruction: To recover the actual sequence of nodes, store parent[next] = curr upon first discovery. When target is reached, trace backward from target to start, then reverse the result.
Graph BFS → Queue FIFO level-by-level ring expansion (Equal-Cost Shortest Path)
Enqueue Rule → Mark visited[neighbor] = true WHEN ENQUEUED (Not when popped!)
Multi-Source BFS → Push ALL initial sources into queue at minute 0 simultaneously
Parent Map → Store parent[next] = curr to trace back actual shortest path sequence
Equal-Cost Only → BFS requires equal edge costs! If weighted, use Dijkstra's algorithm.💡 Golden Rule: "If every move costs the same, BFS explores states in exactly the order of their shortest distance from the start."
Common Interview Mistakes
Marking visited when popping allows duplicate queue insertions when a node has multiple incoming edges! Mark when enqueuing.
Standard BFS only guarantees shortest path when all edge costs are equal! Different weights require Dijkstra's algorithm.
In Multi-Source BFS, enqueue ALL starting sources into the queue before the loop starts. Do NOT run separate BFS calls for each source!
Check if the problem asks for number of edges or sequence length (e.g. Word Ladder counts total words, matrix distance counts edges).
Interview Rules
- 1. Minimum moves / equal-cost shortest path? → Graph BFS
- 2. Queue data structure? → Queue FIFO (using head index in Go)
- 3. When to mark visited? → Mark
visited[neighbor] = trueWHEN ENQUEUED - 4. Multiple starting points? → Multi-Source BFS (enqueue all initial sources at minute 0)
- 5. Actual path sequence required? → Store
parent[next] = currand trace back from target - 6. Large state space + known target? → Bidirectional BFS (meeting in the middle)
- 7. Non-equal weighted edges?→ Dijkstra's Priority Queue algorithm
- 8. Overall Complexity → Time:
O(V + E)| Space:O(V)
Small Rules
- Rule 1: BFS uses a FIFO Queue to expand level by level.
- Rule 2: Always mark nodes as visited when enqueuing to prevent duplicate entries.
- Rule 3: BFS guarantees equal-cost shortest path upon target reach.
- Rule 4: Multi-source BFS pushes all starting nodes into the queue at minute 0.
- Rule 5: Parent map reconstructs the actual shortest path path sequence.
Production Thinking
Network Hop Count Minimization → Finding fewest router hop paths across unweighted network backbones
Social Network Degree of Separation → BFS ring expansion to find 1st, 2nd, and 3rd degree friend connections
Dependency Impact Radius → Determining direct and indirect downstream microservice impact boundaries
Parallel Spreading Event Simulation → Multi-source BFS for epidemic infection or signal propagation modeling
Remember This
Graph BFS → Queue
Visited → Mark when discovered
BFS Wave → Distance 0, 1, 2, 3...
Equal-cost path → BFS
Minimum moves → BFS
Multi-Source → All starts in queue at minute 0
Actual path → Parent map
Weighted edges → Dijkstra
Time → O(V + E)💡 Golden Rule: "If every move costs the same, BFS explores states in exactly the order of their shortest distance from the start."