Shortest Path in Binary Matrix
Shortest Path in Binary Matrix is a medium graphs problem solved with the bfs for shortest path pattern.
The best approach, optimal (bfs), runs in O(n²) time and O(n²) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from dfs exploring all paths up.
Problem
In an n × n binary grid, find the length of the shortest clear path from the top-left to the bottom-right cell, moving in any of 8 directions through 0 cells only. The length counts cells visited. Return -1 if there is no path.
Examples
Example 1
- Input
grid = [[0,0,0],[1,1,0],[1,1,0]]- Output
4
Example 2
- Input
grid = [[1,0],[0,0]]- Output
-1- Why
- The start cell is blocked.
Constraints
1 <= n <= 100; cells are 0 (open) or 1 (blocked).- 8-directional moves; path length counts cells.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| DFS exploring all paths | O(8^(n²)) | O(n²) |
| Optimal (BFS) | O(n²) | O(n²) |
1DFS exploring all paths
O(8^(n²))O(n²)Try every simple path with backtracking and keep the shortest. Correct, but exponential.
- DFS from (0, 0), marking cells on the current path, updating the best when reaching the end.
class Solution {
private int best;
public int shortestPathBinaryMatrix(int[][] grid) {
int n = grid.length;
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
best = Integer.MAX_VALUE;
dfs(grid, 0, 0, 1);
return best == Integer.MAX_VALUE ? -1 : best;
}
private void dfs(int[][] g, int r, int c, int len) {
int n = g.length;
if (len >= best) return;
if (r == n - 1 && c == n - 1) { best = len; return; }
g[r][c] = 1;
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 && g[nr][nc] == 0) dfs(g, nr, nc, len + 1);
}
g[r][c] = 0;
}
}class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:
return -1
self.best = math.inf
self.dfs(grid, 0, 0, 1)
return -1 if self.best == math.inf else self.best
def dfs(self, g: List[List[int]], r: int, c: int, length: int) -> None:
n = len(g)
if length >= self.best:
return
if r == n - 1 and c == n - 1:
self.best = length
return
g[r][c] = 1
for dr in range(-1, 2):
for dc in range(-1, 2):
nr, nc = r + dr, c + dc
if nr >= 0 and nc >= 0 and nr < n and nc < n and g[nr][nc] == 0:
self.dfs(g, nr, nc, length + 1)
g[r][c] = 0class Solution {
int best;
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
int n = grid.size();
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
best = INT_MAX;
dfs(grid, 0, 0, 1);
return best == INT_MAX ? -1 : best;
}
private:
void dfs(vector<vector<int>>& g, int r, int c, int len) {
int n = g.size();
if (len >= best) return;
if (r == n - 1 && c == n - 1) { best = len; return; }
g[r][c] = 1;
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 && g[nr][nc] == 0) dfs(g, nr, nc, len + 1);
}
g[r][c] = 0;
}
};function shortestPathBinaryMatrix(grid) {
const n = grid.length;
if (grid[0][0] === 1 || grid[n - 1][n - 1] === 1) return -1;
let best = Infinity;
function dfs(g, r, c, len) {
if (len >= best) return;
if (r === n - 1 && c === n - 1) { best = len; return; }
g[r][c] = 1;
for (let dr = -1; dr <= 1; dr++)
for (let dc = -1; dc <= 1; dc++) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nc >= 0 && nr < n && nc < n && g[nr][nc] === 0) dfs(g, nr, nc, len + 1);
}
g[r][c] = 0;
}
dfs(grid, 0, 0, 1);
return best === Infinity ? -1 : best;
}2Optimal (BFS)
O(n²)O(n²)BFS from the top-left over 8 directions, storing each cell's distance. The first time the bottom-right is dequeued, its distance is the shortest path length.
- If start or end is blocked, return -1.
- Queue (0, 0) with distance 1; mark visited by setting the cell to 1.
- Expand 8 neighbours; return the distance on reaching the end.
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
int n = grid.length;
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
Queue<int[]> q = new ArrayDeque<>();
q.add(new int[] { 0, 0, 1 });
grid[0][0] = 1;
while (!q.isEmpty()) {
int[] c = q.poll();
if (c[0] == n - 1 && c[1] == n - 1) return c[2];
for (int dr = -1; dr <= 1; dr++)
for (int dc = -1; dc <= 1; dc++) {
int r = c[0] + dr, k = c[1] + dc;
if (r >= 0 && k >= 0 && r < n && k < n && grid[r][k] == 0) {
grid[r][k] = 1;
q.add(new int[] { r, k, c[2] + 1 });
}
}
}
return -1;
}
}class Solution:
def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
n = len(grid)
if grid[0][0] == 1 or grid[n - 1][n - 1] == 1:
return -1
q = deque([(0, 0, 1)])
grid[0][0] = 1
while q:
c = q.popleft()
if c[0] == n - 1 and c[1] == n - 1:
return c[2]
for dr in range(-1, 2):
for dc in range(-1, 2):
r, k = c[0] + dr, c[1] + dc
if r >= 0 and k >= 0 and r < n and k < n and grid[r][k] == 0:
grid[r][k] = 1
q.append((r, k, c[2] + 1))
return -1class Solution {
public:
int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
int n = grid.size();
if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
queue<array<int, 3>> q;
q.push({0, 0, 1});
grid[0][0] = 1;
while (!q.empty()) {
array<int, 3> c = q.front();
q.pop();
if (c[0] == n - 1 && c[1] == n - 1) return c[2];
for (int dr = -1; dr <= 1; dr++)
for (int dc = -1; dc <= 1; dc++) {
int r = c[0] + dr, k = c[1] + dc;
if (r >= 0 && k >= 0 && r < n && k < n && grid[r][k] == 0) {
grid[r][k] = 1;
q.push({r, k, c[2] + 1});
}
}
}
return -1;
}
};function shortestPathBinaryMatrix(grid) {
const n = grid.length;
if (grid[0][0] === 1 || grid[n - 1][n - 1] === 1) return -1;
const q = [[0, 0, 1]];
let head = 0;
grid[0][0] = 1;
while (head < q.length) {
const c = q[head++];
if (c[0] === n - 1 && c[1] === n - 1) return c[2];
for (let dr = -1; dr <= 1; dr++)
for (let dc = -1; dc <= 1; dc++) {
const r = c[0] + dr, k = c[1] + dc;
if (r >= 0 && k >= 0 && r < n && k < n && grid[r][k] === 0) {
grid[r][k] = 1;
q.push([r, k, c[2] + 1]);
}
}
}
return -1;
}Edge cases to test
- Start or end blocked
- n = 1
Hints
Hint 1
Every move costs the same, so BFS reaches the end first along a shortest path.
FAQ
What is the best time complexity for Shortest Path in Binary Matrix?
Optimal (BFS) runs in O(n²) time and O(n²) extra space.
Which pattern does Shortest Path in Binary Matrix use?
It is a graphs problem that uses the bfs for shortest path pattern. Other problems with the same pattern: Word Ladder, Bus Routes, Minimum Knight Moves.
Is there a brute force solution for Shortest Path in Binary Matrix?
Yes. DFS exploring all paths takes O(8^(n²)) time and O(n²) space. Try every simple path with backtracking and keep the shortest.
Which edge cases should I test for Shortest Path in Binary Matrix?
Start or end blocked; n = 1.