Shortest Path in Binary Matrix
Medium
Topics
Given a binary matrix grid, return the length of the shortest clear path from the top-left cell to the bottom-right cell, or -1 if none exists. A clear path visits only cells with value 0 and may move in any of the 8 directions. Path length is the number of visited cells.
Example 1
Input: grid = [[0,1],[1,0]] Output: 2
Example 2
Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4
Constraints
- 1 <= m, n <= 100
- grid[i][j] is 0 or 1.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Every move costs the same one cell, so the shortest path is a breadth-first search — no weights, no priority queue, no Dijkstra. The only twists are that movement is 8-directional rather than 4, and that the answer counts cells visited rather than steps taken, so the start cell already counts as 1.
Expanding level by level means the distance is the level index, which removes the need to store a distance per cell. Mark a cell visited when it is queued, not when it is dequeued — otherwise the same cell is reached from up to eight neighbours and enters the queue repeatedly. On a 100×100 open grid that is the difference between queueing 9,999 cells and queueing 39,402.
Approach
- Reject immediately if either corner is blocked.
- Seed the frontier with the top-left cell, marked visited, at length 1.
- For each cell in the current frontier, return the current length if it is the bottom-right cell.
- Otherwise queue every unvisited open neighbour among the 8 directions, marking each as it is queued.
- Increment the length and repeat with the new frontier. An empty frontier means no path, so return -1.
Dry Run
grid 0 0 0
1 1 0
1 1 0
layer cells at this distance
1 (0,0)
2 (0,1)
3 (0,2) (1,2)
4 (2,2) <- bottom-right reached
answer 4
[[0,1],[1,0]] -> 2 the diagonal is a legal move
[[1,0,0],[1,1,0],[1,1,0]] -> -1 start is blocked
[[0]] -> 1 a single open cell is a path of one cell
[[0,0],[1,1]] -> -1 no route to the cornerComplexity
- Time — O(m·n): each cell is marked once and its 8 neighbours are examined once.
- Space — O(m·n) for the visited grid and the frontier. Reusing a copy of the input as the visited marker avoids a second allocation; mutating the caller's grid avoids even that, at the cost of a side effect worth mentioning out loud.
Common Pitfalls
- Marking cells visited on dequeue rather than on enqueue. With 8 neighbours the same cell is queued many times over; measured on a 100×100 open grid, the queue takes 39,402 entries instead of 9,999. The answer stays correct, so this is a silent 4× cost.
- Using depth-first search. DFS finds a path, not the shortest one, and on a grid it typically finds a terrible one.
- Reaching for Dijkstra or A*. Every edge has weight 1, which is precisely the condition under which BFS already gives the optimum; A* with a Chebyshev-distance heuristic is a legitimate speedup to mention, but plain BFS is the expected answer.
- Counting steps instead of cells, which is off by one: a single open cell answers 1, not 0.
- Only checking 4 directions, or writing the 8 offsets by hand and omitting one. Deriving them as all
(dr, dc)withdr, dcin{-1,0,1}excluding(0,0)is harder to get wrong. - Forgetting to test the destination when the grid is a single cell, where start and end coincide and the loop must return on the very first frontier.
Full Solution — all languages
class Solution:
def shortestPathBinaryMatrix(self, grid):
R, C = len(grid), len(grid[0])
if grid[0][0] != 0 or grid[R-1][C-1] != 0:
return -1
dirs = [(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]
vis = [row[:] for row in grid]
vis[0][0] = 1
q = [(0, 0)]
length = 1
while q:
nq = []
for r, c in q:
if r == R-1 and c == C-1:
return length
for dr, dc in dirs:
nr, nc = r+dr, c+dc
if 0 <= nr < R and 0 <= nc < C and vis[nr][nc] == 0:
vis[nr][nc] = 1
nq.append((nr, nc))
length += 1
q = nq
return -1import java.util.*;
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
int R = grid.length, C = grid[0].length;
if (grid[0][0] != 0 || grid[R-1][C-1] != 0) return -1;
int[][] dirs = { {
1,0
},
{
-1,0
},
{
0,1
},
{
0,-1
},
{
1,1
},
{
1,-1
},
{
-1,1
},
{
-1,-1
}
};
int[][] vis = new int[R][C];
for (int r = 0; r < R; r++) vis[r] = grid[r].clone();
vis[0][0] = 1;
ArrayDeque<int[]> q = new ArrayDeque<>();
q.add(new int[]{0, 0});
int length = 1;
while (!q.isEmpty()) {
ArrayDeque<int[]> nq = new ArrayDeque<>();
for (int[] cur : q) {
if (cur[0] == R-1 && cur[1] == C-1) return length;
for (int[] d : dirs) {
int nr = cur[0] + d[0], nc = cur[1] + d[1];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && vis[nr][nc] == 0) {
vis[nr][nc] = 1;
nq.add(new int[]{nr, nc});
}
}
}
length++;
q = nq;
}
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size();
if (grid[0][0] != 0 || grid[R-1][C-1] != 0) return -1;
int dirs[8][2] = { {
1,0
},
{
-1,0
},
{
0,1
},
{
0,-1
},
{
1,1
},
{
1,-1
},
{
-1,1
},
{
-1,-1
}
};
vector<vector<int>> vis = grid;
vis[0][0] = 1;
vector<pair<int,int>> q = { {
0, 0
}
};
int length = 1;
while (!q.empty()) {
vector<pair<int,int>> nq;
for (auto& cur : q) {
if (cur.first == R-1 && cur.second == C-1) return length;
for (int d = 0; d < 8; d++) {
int nr = cur.first + dirs[d][0], nc = cur.second + dirs[d][1];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && vis[nr][nc] == 0) {
vis[nr][nc] = 1;
nq.push_back({nr, nc});
}
}
}
length++;
q = nq;
}
return -1;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var shortestPathBinaryMatrix = function(grid) {
const R = grid.length, C = grid[0].length;
if (grid[0][0] !== 0 || grid[R-1][C-1] !== 0) return -1;
const dirs = [[1,0],[-1,0],[0,1],[0,-1],[1,1],[1,-1],[-1,1],[-1,-1]];
const vis = grid.map(row => row.slice());
vis[0][0] = 1;
let q = [[0, 0]], length = 1;
while (q.length) {
const nq = [];
for (const [r, c] of q) {
if (r === R-1 && c === C-1) return length;
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < R && nc >= 0 && nc < C && vis[nr][nc] === 0) {
vis[nr][nc] = 1;
nq.push([nr, nc]);
}
}
}
length++;
q = nq;
}
return -1;
};