Shortest Path in Binary Matrix

Medium Graphs BFS for shortest path Original on LeetCode

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.

00:00
Testcase

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.

ApproachTimeSpace
DFS exploring all pathsO(8^(n²))O(n²)
Optimal (BFS)O(n²)O(n²)

1DFS exploring all paths

TimeO(8^(n²))
SpaceO(n²)

Try every simple path with backtracking and keep the shortest. Correct, but exponential.

  1. 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;
    }
}

2Optimal (BFS)

TimeO(n²)
SpaceO(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.

  1. If start or end is blocked, return -1.
  2. Queue (0, 0) with distance 1; mark visited by setting the cell to 1.
  3. 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;
    }
}

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.