Graphs · Pattern 4 of 14
BFS for the shortest path
When every move costs 1, BFS reaches each node first along a shortest path. Count the levels until you pop the target. The node can be a cell, a word, a whole board or a cell plus extra state.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Minimum number of moves, steps or transformations
- Every move has the same cost
- The "node" is a state you can build: a string, a board, a position plus keys
The template
int shortestPathBinaryMatrix(int[][] grid) {
int n = grid.length;
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
Deque<int[]> q = new ArrayDeque<>();
q.offer(new int[]{0, 0});
grid[0][0] = 1; // mark visited when you push
for (int dist = 1; !q.isEmpty(); dist++) {
for (int size = q.size(); size > 0; size--) { // everything at this distance
int[] cur = q.poll();
if (cur[0] == n - 1 && cur[1] == n - 1) return dist;
for (int dr = -1; dr <= 1; dr++)
for (int dc = -1; dc <= 1; dc++) { // 8 directions
int r = cur[0] + dr, c = cur[1] + dc;
if (r >= 0 && c >= 0 && r < n && c < n && grid[r][c] == 0) {
grid[r][c] = 1;
q.offer(new int[]{r, c});
}
}
}
}
return -1;
}
// state BFS: the nodes are strings, and the neighbours are built on the fly
int openLock(String[] deadends, String target) {
Set<String> seen = new HashSet<>(Arrays.asList(deadends));
if (!seen.add("0000")) return -1; // the start itself is dead
Deque<String> q = new ArrayDeque<>(List.of("0000"));
for (int steps = 0; !q.isEmpty(); steps++) {
for (int size = q.size(); size > 0; size--) {
String s = q.poll();
if (s.equals(target)) return steps;
char[] c = s.toCharArray();
for (int i = 0; i < 4; i++) {
char orig = c[i];
for (int d : new int[]{1, 9}) { // turn wheel i up or down
c[i] = (char) ('0' + (orig - '0' + d) % 10);
String next = new String(c);
if (seen.add(next)) q.offer(next);
}
c[i] = orig;
}
}
}
return -1;
} from collections import deque
def shortest_path_binary_matrix(grid):
n = len(grid)
if grid[0][0] or grid[n - 1][n - 1]:
return -1
q, dist = deque([(0, 0)]), 1
grid[0][0] = 1 # mark visited when you push
while q:
for _ in range(len(q)): # everything at this distance
r, c = q.popleft()
if r == n - 1 and c == n - 1:
return dist
for dr in (-1, 0, 1): # 8 directions
for dc in (-1, 0, 1):
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0:
grid[nr][nc] = 1
q.append((nr, nc))
dist += 1
return -1
def open_lock(deadends, target): # state BFS: nodes are strings built on the fly
seen = set(deadends)
if "0000" in seen:
return -1
seen.add("0000")
q, steps = deque(["0000"]), 0
while q:
for _ in range(len(q)):
s = q.popleft()
if s == target:
return steps
for i in range(4):
for d in (1, 9): # turn wheel i up or down
nxt = s[:i] + str((int(s[i]) + d) % 10) + s[i + 1:]
if nxt not in seen:
seen.add(nxt)
q.append(nxt)
steps += 1
return -1 int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
int n = grid.size();
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
queue<pair<int, int>> q;
q.push({0, 0});
grid[0][0] = 1; // mark visited when you push
for (int dist = 1; !q.empty(); dist++) {
for (int size = q.size(); size > 0; size--) { // everything at this distance
auto [r, c] = q.front(); q.pop();
if (r == n - 1 && c == n - 1) return dist;
for (int dr = -1; dr <= 1; dr++)
for (int dc = -1; dc <= 1; dc++) { // 8 directions
int nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < n && nc < n && grid[nr][nc] == 0) {
grid[nr][nc] = 1;
q.push({nr, nc});
}
}
}
}
return -1;
}
// state BFS: the nodes are strings, and the neighbours are built on the fly
int openLock(vector<string>& deadends, string target) {
unordered_set<string> seen(deadends.begin(), deadends.end());
if (!seen.insert("0000").second) return -1; // the start itself is dead
queue<string> q;
q.push("0000");
for (int steps = 0; !q.empty(); steps++) {
for (int size = q.size(); size > 0; size--) {
string s = q.front(); q.pop();
if (s == target) return steps;
for (int i = 0; i < 4; i++) {
char orig = s[i];
for (int d : {1, 9}) { // turn wheel i up or down
s[i] = '0' + (orig - '0' + d) % 10;
if (seen.insert(s).second) q.push(s);
}
s[i] = orig;
}
}
}
return -1;
} function shortestPathBinaryMatrix(grid) {
const n = grid.length;
if (grid[0][0] === 1 || grid[n - 1][n - 1] === 1) return -1;
let q = [[0, 0]];
grid[0][0] = 1; // mark visited when you push
for (let dist = 1; q.length; dist++) {
const next = []; // everything at distance + 1
for (const [r, c] of q) {
if (r === n - 1 && c === n - 1) return dist;
for (let dr = -1; dr <= 1; dr++)
for (let dc = -1; dc <= 1; dc++) { // 8 directions
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < n && nc < n && grid[nr][nc] === 0) {
grid[nr][nc] = 1;
next.push([nr, nc]);
}
}
}
q = next;
}
return -1;
}
// state BFS: the nodes are strings, and the neighbours are built on the fly
function openLock(deadends, target) {
const seen = new Set(deadends);
if (seen.has('0000')) return -1;
seen.add('0000');
let q = ['0000'];
for (let steps = 0; q.length; steps++) {
const next = [];
for (const s of q) {
if (s === target) return steps;
for (let i = 0; i < 4; i++)
for (const d of [1, 9]) { // turn wheel i up or down
const t = s.slice(0, i) + ((+s[i] + d) % 10) + s.slice(i + 1);
if (!seen.has(t)) { seen.add(t); next.push(t); }
}
}
q = next;
}
return -1;
} The variations
-
1Shortest path on a grid or board
Cells are nodes and allowed moves are edges: 8 directions, knight jumps, or a die roll plus a snake or ladder. Count BFS levels until you pop the target.
Now you solve- Minimum Knight Moves Medium Stuck? solution
- Snakes and Ladders Medium Stuck? solution
-
2Strings as nodes
Each word or lock code is a node; change one letter or one wheel to get a neighbour, and keep only the ones in the dictionary and not yet seen. For all shortest ladders, record each word's parents level by level, then backtrack from the end.
Now you solve- Open the Lock Medium Stuck? solution
- Word Ladder II Hard Stuck? solution
-
3The whole board is the state
Encode the board as a string or a bitmask (a 2 × 3 puzzle, a small 0/1 matrix, a row of balls plus a hand). Every legal move gives a neighbouring state. The state space is small, so plain BFS finds the fewest moves.
Now you solve -
4Position plus extra state
The node is (row, col, something): obstacles you may still remove, or a bitmask of keys collected. Two visits to the same cell with different extras are different nodes.
Now you solve -
5BFS over groups
When one step lets you reach a whole group (every stop on a bus route), make the groups the nodes. Map each stop to its routes, and mark a route as used the first time you board it so you never scan it again.
Mistakes to avoid
- Marking visited on pop: on a grid the same cell gets queued from several neighbours and the queue blows up.
- Visiting a position only once when the state has more to it (obstacles left, keys held). The visited set must hold the whole state, not only the cell.
- Word ladder: comparing every pair of words is O(n²·L). Generate neighbours by changing each letter to a–z and looking them up in a set instead.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.