Shortest Path in Binary Matrix (LeetCode 1091): Solution and Explanation
In an n × n grid of 0s and 1s, find the length of the shortest path from the top-left cell to the bottom-right cell that only steps on 0 cells. Moves can go in all eight directions, the length counts cells visited, and you return -1 if no such path exists.
Watch it run step by step
Try your own input and write the code →Intuition
Shortest path on an unweighted grid is a classic BFS problem. A DFS could find some path but would need to explore every path to be sure it found the shortest, which is exponential. BFS instead explores cells in order of distance from the start: first the start, then every cell one step away, then every cell two steps away. The first time it reaches the target, that distance is guaranteed to be the minimum.
Two details distinguish this problem. Movement is 8-directional, so each cell has up to eight neighbors including diagonals, and the path length counts cells rather than moves, so the start cell already has length 1. If the start or the end cell is blocked, there is nothing to search and the answer is -1 immediately.
To keep BFS linear, every cell must be enqueued at most once. The reference code marks a cell as visited the moment it is added to the queue, not when it is removed. That way, two different neighbors cannot both enqueue the same cell, and the first enqueue, which happens at the smallest distance, is the one that counts.
Storing the distance alongside each cell in the queue keeps the code simple. An equivalent style processes the queue level by level and increments a single counter after each level, which some people find easier to explain. Either way the distances in the queue are non-decreasing, which is the property that makes the first arrival at the target the shortest one.
Approach: Breadth-first search with 8 directions
- If
grid[0][0]orgrid[n - 1][n - 1]is 1, return -1. - List the eight direction offsets and start a deque with
(0, 0, 1), marking(0, 0)visited. - Pop
(r, c, dist); if it is the bottom-right cell, returndist. - For each direction, compute
(nr, nc)and check it is in bounds, is 0 and is not visited. - Mark it visited and append
(nr, nc, dist + 1). - If the queue empties, return -1.
Step-by-step example
grid = [[0,0,0],[1,1,0],[1,1,0]]
- The queue starts with
(0, 0, 1). Its only open neighbor is(0, 1), which is enqueued with distance 2. - Popping
(0, 1, 2), the open unvisited neighbors are(0, 2)and the diagonal(1, 2), both enqueued with distance 3. - Popping
(0, 2, 3)adds nothing new, because(1, 2)is already visited and(1, 1)is blocked. - Popping
(1, 2, 3)enqueues(2, 2)with distance 4; the other neighbors are blocked or visited. - Popping
(2, 2, 4)reaches the target, so the answer is 4.
Code: Python, Java, C++
1class Solution:
2 def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
3 n = len(grid)
4 if grid[0][0] == 1 or grid[n-1][n-1] == 1:
5 return -1
6
7 directions = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
8 queue = deque([(0, 0, 1)])
9 visited = {(0, 0)}
10
11 while queue:
12 r, c, dist = queue.popleft()
13 if r == n-1 and c == n-1:
14 return dist
15
16 for dr, dc in directions:
17 nr, nc = r + dr, c + dc
18 if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0 and (nr, nc) not in visited:
19 visited.add((nr, nc))
20 queue.append((nr, nc, dist + 1))
21
22 return -11class Solution {
2 public int shortestPathBinaryMatrix(int[][] grid) {
3 int n = grid.length;
4 if (grid[0][0] == 1 || grid[n-1][n-1] == 1) return -1;
5
6 int[][] directions = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
7 Queue<int[]> queue = new LinkedList<>();
8 queue.offer(new int[]{0, 0, 1});
9 boolean[][] visited = new boolean[n][n];
10 visited[0][0] = true;
11
12 while (!queue.isEmpty()) {
13 int[] curr = queue.poll();
14 int r = curr[0], c = curr[1], dist = curr[2];
15 if (r == n-1 && c == n-1) return dist;
16
17 for (int[] d : directions) {
18 int nr = r + d[0], nc = c + d[1];
19 if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0 && !visited[nr][nc]) {
20 visited[nr][nc] = true;
21 queue.offer(new int[]{nr, nc, dist + 1});
22 }
23 }
24 }
25
26 return -1;
27 }
28}1class Solution {
2public:
3 int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
4 int n = grid.size();
5 if (grid[0][0] == 1 || grid[n-1][n-1] == 1) return -1;
6
7 vector<pair<int,int>> directions = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
8 queue<tuple<int,int,int>> q;
9 q.push({0, 0, 1});
10 vector<vector<bool>> visited(n, vector<bool>(n, false));
11 visited[0][0] = true;
12
13 while (!q.empty()) {
14 auto [r, c, dist] = q.front();
15 q.pop();
16 if (r == n-1 && c == n-1) return dist;
17
18 for (auto [dr, dc] : directions) {
19 int nr = r + dr, nc = c + dc;
20 if (nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0 && !visited[nr][nc]) {
21 visited[nr][nc] = true;
22 q.push({nr, nc, dist + 1});
23 }
24 }
25 }
26
27 return -1;
28 }
29};Time and space complexity
O(n²)
Each of the n² cells is enqueued at most once, and each dequeue checks eight neighbors.
O(n²)
The visited set and the queue can each hold up to n² cells.
Other approaches
BFS marking the grid in place (time O(n²), space O(n²))
Set grid[nr][nc] = 1 instead of using a visited set. It saves memory but modifies the input, which you should mention in an interview.
A* search (time O(n² log n), space O(n²))
Prioritize cells by distance so far plus the Chebyshev distance to the target. It explores fewer cells in open grids, though the worst case is the same and it needs a heap.
Common mistakes
- Using only four directions, which misses diagonal shortcuts and returns a longer path or -1.
- Starting the distance at 0 instead of 1; the length counts cells, so a 1 × 1 grid of [[0]] should return 1.
- Marking cells visited when dequeued rather than when enqueued, which lets the same cell be added many times and slows the search.
- Skipping the check that the start or end cell is blocked, which can return a path length for an impossible grid.
Frequently asked questions
Why use BFS for shortest path in binary matrix?
Every move costs the same, and BFS visits cells in increasing distance order. The first time it reaches the target is therefore the shortest path.
Does the path length count cells or moves?
It counts cells, including the start and the end. That is why the BFS starts with distance 1 at the top-left cell.
Why not DFS?
DFS finds a path but not necessarily the shortest one. To guarantee the minimum it would need to explore all paths, which is exponential.
What is the time complexity?
O(n²) time and space for an n × n grid, since each cell is enqueued once and has at most eight neighbors.