Algo-Sim › Grid Graphs
Shortest Path in Binary Matrix
Medium · Grid Graphs · step through it in Java, Python and C++ on your own input
In an n×n grid of 0 (open) and 1 (blocked), return the number of cells on the shortest 8-directional path from the top-left to the bottom-right, or -1.
Problem
In an n × n grid of 0 (open) and 1 (blocked), find the shortest path from the top-left cell to the bottom-right cell that only visits open cells, moving in any of the 8 directions. Return the number of cells on that path, or -1 if there is none.
Constraints
- 1 ≤ n ≤ 100
- grid[i][j] is 0 or 1
- A blocked start or end means −1
- Every move costs 1, so BFS finds the shortest path
Edge cases to test
- The start or end cell is blocked:
-1 - 1 × 1 grid with 0:
1 - Diagonal moves are allowed
Follow-up questions
- Why BFS and not DFS?
- All moves cost 1, so BFS reaches the goal first along a shortest path; DFS would need to explore everything.
- How can A* help?
- With Chebyshev distance as the heuristic it explores fewer cells while staying optimal.
Solution
Java
public int shortestPathBinaryMatrix(int[][] grid) {
int n = grid.length;
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
int[][] dist = new int[n][n];
dist[0][0] = 1;
Queue<int[]> queue = new ArrayDeque<>();
queue.offer(new int[] { 0, 0 });
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int r = cell[0], c = cell[1];
if (r == n - 1 && c == n - 1) return dist[r][c];
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr < 0 || nc < 0 || nr >= n || nc >= n || grid[nr][nc] == 1 || dist[nr][nc] > 0) continue;
dist[nr][nc] = dist[r][c] + 1;
queue.offer(new int[] { nr, nc });
}
}
}
return -1;
}Python
from collections import deque
def shortest_path_binary_matrix(grid):
n = len(grid)
if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:
return -1
dist = [[0] * n for _ in range(n)]
dist[0][0] = 1
queue = deque([(0, 0)])
while queue:
r, c = queue.popleft()
if r == n - 1 and c == n - 1:
return dist[r][c]
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
nr, nc = r + dr, c + dc
if not (0 <= nr < n and 0 <= nc < n) or grid[nr][nc] == 1 or dist[nr][nc] > 0:
continue
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
return -1C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>> &grid) {
int n = int(grid.size());
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1)
return -1;
vector<vector<int>> dist = vector<vector<int>>(n, vector<int>(n));
dist[0][0] = 1;
deque<vector<int>> queue = {};
queue.push_back(vector<int>{0, 0});
while (!queue.empty()) {
vector<int> cell = queue.front();
queue.pop_front();
int r = cell[0], c = cell[1];
if (r == n - 1 && c == n - 1)
return dist[r][c];
for (int dr = -1; dr <= 1; dr++) {
for (int dc = -1; dc <= 1; dc++) {
int nr = r + dr, nc = c + dc;
if (nr < 0 || nc < 0 || nr >= n || nc >= n || grid[nr][nc] == 1 || dist[nr][nc] > 0)
continue;
dist[nr][nc] = dist[r][c] + 1;
queue.push_back(vector<int>{nr, nc});
}
}
}
return -1;
}
};
More Grid Graphs problems
- Flood Fill (Easy)
- Number of Islands (BFS) (Medium)
- Number of Islands (DFS) (Medium)
- Max Area of Island (Medium)
- Rotting Oranges (Medium)
- 01 Matrix (Medium)
- Walls and Gates (Medium)
- Shortest Bridge (Medium)
- Shortest Path in a Grid with Obstacles Elimination (Hard)
- Surrounded Regions (Medium)
- Pacific Atlantic Water Flow (Medium)
- Path With Minimum Effort (Medium)
- Minimum Cost to Make at Least One Valid Path in a Grid (Hard)
- Swim in Rising Water (Hard)