1091. Shortest Path in Binary Matrix
Asked at 13Meta80Bloomberg40Amazon38Google36Microsoft32Apple30Anduril69Applied Intuition48Snap45Databricks44Airbnb38TikTok35Uber30
Problem
In an n×n binary grid, find the shortest clear path from the top-left to the bottom-right cell: it visits only 0 cells and moves in any of the 8 directions. Return its length in cells, or −1 if there is none.
Example: [[0,1],[1,0]] → 2; [[0,0,0],[1,1,0],[1,1,0]] → 4
Constraints: n ≤ 100.
BFS over 8 directions from (0,0) to (n−1,n−1); path length counts cells.
Complexity: O(n²).
class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] or grid[n - 1][n - 1]:
return -1
q = deque([(0, 0, 1)])
grid[0][0] = 1
while q:
r, c, d = q.popleft()
if r == c == n - 1:
return d
for dr in (-1, 0, 1):
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, d + 1))
return -1
assert Solution().shortestPathBinaryMatrix([[0, 1], [1, 0]]) == 2
assert Solution().shortestPathBinaryMatrix([[0, 0, 0], [1, 1, 0], [1, 1, 0]]) == 4
assert Solution().shortestPathBinaryMatrix([[1, 0, 0], [1, 1, 0], [1, 1, 0]]) == -1
class Solution {
public 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.add(new int[]{0, 0, 1});
grid[0][0] = 1;
while (!q.isEmpty()) {
int[] cur = q.poll();
if (cur[0] == n - 1 && cur[1] == n - 1) return cur[2];
for (int dr = -1; dr <= 1; dr++)
for (int dc = -1; dc <= 1; dc++) {
int nr = cur[0] + dr, nc = cur[1] + dc;
if (nr >= 0 && nc >= 0 && nr < n && nc < n && grid[nr][nc] == 0) {
grid[nr][nc] = 1;
q.add(new int[]{nr, nc, cur[2] + 1});
}
}
}
return -1;
}
}
func shortestPathBinaryMatrix(grid [][]int) int {
n := len(grid)
if grid[0][0] == 1 || grid[n-1][n-1] == 1 {
return -1
}
q := [][3]int{{0, 0, 1}} // (r, c, path length)
grid[0][0] = 1
for len(q) > 0 {
p := q[0]
q = q[1:]
if p[0] == n-1 && p[1] == n-1 {
return p[2]
}
for dr := -1; dr <= 1; dr++ { // 8 directions
for dc := -1; dc <= 1; dc++ {
nr, nc := p[0]+dr, p[1]+dc
if nr >= 0 && nr < n && nc >= 0 && nc < n && grid[nr][nc] == 0 {
grid[nr][nc] = 1
q = append(q, [3]int{nr, nc, p[2] + 1})
}
}
}
}
return -1
}