Shortest path with BFS
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Breadth-first search guarantees finding the shortest path in unweighted graphs by exploring nodes in order of distance.
Why BFS guarantees shortest unweighted paths
In an unweighted graph, every edge represents exactly 1 unit of distance. Depth-first search dives deeply down arbitrary branches. Consequently, DFS can discover an unnecessarily long detour before finding a direct connection.
Example 1 · Brute force: try every path with DFS, exponential time
public class Main { static int best = Integer.MAX_VALUE;
static void dfs(int[][] g, int r, int c, int steps, boolean[][] seen) { if (r < 0 || c < 0 || r >= g.length || c >= g[0].length) return; if (g[r][c] == 1 || seen[r][c]) return; if (r == g.length - 1 && c == g[0].length - 1) { best = Math.min(best, steps); return; } seen[r][c] = true; dfs(g, r + 1, c, steps + 1, seen); dfs(g, r - 1, c, steps + 1, seen); dfs(g, r, c + 1, steps + 1, seen); dfs(g, r, c - 1, steps + 1, seen); seen[r][c] = false; // backtrack so other paths may reuse this cell }
public static void main(String[] args) { int[][] grid = { {0, 0, 0}, {1, 1, 0}, {0, 0, 0} }; dfs(grid, 0, 0, 0, new boolean[3][3]); System.out.println("Min grid steps: " + (best == Integer.MAX_VALUE ? -1 : best)); }}Min grid steps: 4
What this code does
- DFS follows one path to the end, then backtracks and tries the next, keeping the shortest length found.
- Because cells can be reused by different paths, the number of paths grows exponentially.
- BFS visits each cell once, in order of distance, so the first arrival is already the shortest.
Example 2 · Optimal: BFS on the grid, O(rows * cols) time and space
import java.util.*;
public class Main { static int minStepsInGrid(int[][] grid) { int rows = grid.length, cols = grid[0].length; if (grid[0][0] == 1 || grid[rows - 1][cols - 1] == 1) return -1;
int[] dr = {-1, 1, 0, 0}; int[] dc = {0, 0, -1, 1};
Queue<int[]> q = new LinkedList<>(); grid[0][0] = 1; // Mark visited q.offer(new int[]{0, 0, 0}); // r, c, dist
while (!q.isEmpty()) { int[] curr = q.poll(); int r = curr[0], c = curr[1], dist = curr[2]; if (r == rows - 1 && c == cols - 1) return dist;
for (int k = 0; k < 4; k++) { int nr = r + dr[k], nc = c + dc[k]; if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 0) { grid[nr][nc] = 1; // Mark visited q.offer(new int[]{nr, nc, dist + 1}); } } } return -1; }
public static void main(String[] args) { int[][] grid = { {0, 0, 0}, {1, 1, 0}, {0, 0, 0} }; System.out.println("Min grid steps: " + minStepsInGrid(grid)); }}Min grid steps: 4
What this code does
- Queue stores row, column, and accumulated step count for each position.
- 4-directional moves navigate around the barrier cells to destination (2,2).
- Returns minimum step count 4 upon first dequeue of the destination.
- BFS reaches cells in order of distance, so the first time it arrives is already the shortest; no path is explored twice.
Breadth-first search radiates outwards level by level using a FIFO queue. It visits all vertices at distance 1 before any vertex at distance 2. Nodes are visited in non-decreasing distance order. Therefore, the first discovery of any vertex gives its shortest path. An integer array dist initialised to -1 tracks minimum distances. When vertex u discovers unvisited neighbour v, set dist[v] = dist[u] + 1. This computes optimal distances for all reachable nodes in O(V + E) time.
Predict the output
Predict the BFS distances
Read the code and pick what it prints.
What does this program print?
Reconstructing the shortest path using parent pointers
Finding the minimum hop distance is often only the first part of solving a problem. Engineers usually need the actual sequence of vertices along the shortest path. We record this route by maintaining a parent array initialised to -1.
Example 3 · Reconstructing the Shortest Path in Java
import java.util.*;
public class Main { static List<Integer> shortestPath(int n, List<List<Integer>> adj, int start, int target) { int[] parent = new int[n]; Arrays.fill(parent, -1); boolean[] vis = new boolean[n];
Queue<Integer> q = new LinkedList<>(); vis[start] = true; q.offer(start);
while (!q.isEmpty()) { int u = q.poll(); if (u == target) break;
for (int v : adj.get(u)) { if (!vis[v]) { vis[v] = true; parent[v] = u; q.offer(v); } } }
if (!vis[target]) return Collections.emptyList();
List<Integer> path = new ArrayList<>(); for (int curr = target; curr != -1; curr = parent[curr]) { path.add(curr); } Collections.reverse(path); return path; }
public static void main(String[] args) { int n = 5; List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); adj.get(0).addAll(Arrays.asList(1, 2)); adj.get(1).addAll(Arrays.asList(0, 3)); adj.get(2).addAll(Arrays.asList(0, 4)); adj.get(3).addAll(Arrays.asList(1, 4)); adj.get(4).addAll(Arrays.asList(2, 3));
System.out.println("Shortest path 0 to 4: " + shortestPath(n, adj, 0, 4)); }}Shortest path 0 to 4: [0, 2, 4]
What this code does
- parent array links each newly discovered node back to its predecessor.
- Backtracking from node 4 follows parent pointers to 2 and then to 0.
- Reversing the collected path yields the forward route [0, 2, 4].
Whenever vertex u discovers an unvisited neighbour v, record parent[v] = u. After BFS reaches the target destination, backtrack from destination to start using parent pointers. Collect vertices into a list during backtracking, then reverse the list. This produces the exact forward sequence of vertices in O(path length) time. If parent[target] remains -1, no connecting path exists between the endpoints.
Word Ladder: Modelling words as an implicit unweighted graph
The Word Ladder problem transforms a start word into a target word. Each step changes exactly one letter, and every intermediate word must exist in a dictionary.
Example 4 · Word Ladder BFS Transformation in Java
import java.util.*;
public class Main { static int ladderLength(String beginWord, String endWord, List<String> wordList) { Set<String> dict = new HashSet<>(wordList); if (!dict.contains(endWord)) return 0;
Queue<String> q = new LinkedList<>(); q.offer(beginWord); int level = 1;
while (!q.isEmpty()) { int size = q.size(); for (int s = 0; s < size; s++) { String curr = q.poll(); if (curr.equals(endWord)) return level;
char[] chars = curr.toCharArray(); for (int i = 0; i < chars.length; i++) { char orig = chars[i]; for (char c = 'a'; c <= 'z'; c++) { chars[i] = c; String next = new String(chars); if (dict.contains(next)) { dict.remove(next); // Mark visited q.offer(next); } } chars[i] = orig; } } level++; } return 0; }
public static void main(String[] args) { List<String> words = Arrays.asList("hot", "dot", "dog", "lot", "log", "cog"); System.out.println("Ladder length hit->cog: " + ladderLength("hit", "cog", words)); }}Ladder length hit->cog: 5
What this code does
- dict set allows O(1) word lookup and removal to prevent duplicate cycles.
- Single character mutations are generated dynamically across 26 alphabet letters.
- Shortest sequence hit -> hot -> dot -> dog -> cog contains 5 words.
We model this problem as an unweighted graph where dictionary words form vertices. An edge connects two words if they differ by exactly one character. Finding the shortest transformation sequence is equivalent to finding the shortest path in this implicit graph. At each step, poll the current word from the BFS queue. Generate all 26 possible single-character mutations for each character position. If a mutated word exists in the dictionary, enqueue it and remove it from the dictionary set. This prevents revisiting words and ensures O(M^2 * N) optimal runtime.
Next step
Check your understanding
10 quick questions