Shortest Path in Binary Matrix

Pattern: Shortest paths

medium

Move through 0-cells in any of 8 directions from the top-left to the bottom-right. Every step costs one cell, so BFS from the top-left gives the fewest cells; the length counts both ends.

The problem

Given an n × n grid of 0 (open) and 1 (blocked), return the number of cells on the shortest path from the top-left to the bottom-right through open cells, moving in any of 8 directions, or -1 if there is none.

Think first

  • How many neighbours does a cell have here?
  • What if the start or end is blocked?
  • Does the length count cells or moves?

Hints

    Brute force, and why it fails

    DFS over every path: exponential.

    The key insight

    All moves cost the same, so BFS finds the shortest path, visiting each cell once.

    Dry run

    length1

    grid [[0, 0, 0], [1, 1, 0], [1, 1, 0]]. Start (0, 0), length 1.

    Step 1 of 3

    The plan

    if start or end blocked: -1
    BFS from (0, 0) with length 1 over the 8 directions
    

    Complexity

    Time
    O(n²)
    Space
    O(n²)

    Each cell once.

    Edge cases

    • A 1 × 1 grid of 0: 1.
    • Blocked start: -1.
    • A diagonal path.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        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];           // the path length counts cells, so the start is 1
            dist[0][0] = 1;
            Queue<int[]> q = new ArrayDeque<>();
            q.add(new int[]{0, 0});
            while (!q.isEmpty()) {
                int[] cur = q.poll();
                if (cur[0] == n - 1 && cur[1] == n - 1) return dist[cur[0]][cur[1]];
                for (int dr = -1; dr <= 1; dr++)
                    for (int dc = -1; dc <= 1; dc++) {          // eight directions
                        int r = cur[0] + dr, c = cur[1] + dc;
                        if (r >= 0 && c >= 0 && r < n && c < n && grid[r][c] == 0 && dist[r][c] == 0) {
                            dist[r][c] = dist[cur[0]][cur[1]] + 1;
                            q.add(new int[]{r, c});
                        }
                    }
            }
            return -1;
        }
    }

    C++

    class Solution {
    public:
        int shortestPathBinaryMatrix(vector<vector<int>>& grid) {
            int n = static_cast<int>(grid.size());
            if (grid[0][0] == 1 || grid[n - 1][n - 1] == 1) return -1;
            vector<vector<int>> dist(n, vector<int>(n, 0));   // the path length counts cells, so the start is 1
            dist[0][0] = 1;
            queue<pair<int, int>> q;
            q.push(make_pair(0, 0));
            while (!q.empty()) {
                pair<int, int> cur = q.front();
                q.pop();
                if (cur.first == n - 1 && cur.second == n - 1) return dist[cur.first][cur.second];
                for (int dr = -1; dr <= 1; dr++)
                    for (int dc = -1; dc <= 1; dc++) {          // eight directions
                        int r = cur.first + dr, c = cur.second + dc;
                        if (r >= 0 && c >= 0 && r < n && c < n && grid[r][c] == 0 && dist[r][c] == 0) {
                            dist[r][c] = dist[cur.first][cur.second] + 1;
                            q.push(make_pair(r, c));
                        }
                    }
            }
            return -1;
        }
    };

    Python

    from collections import deque
    
    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
            dist = {(0, 0): 1}                      # the path length counts cells, so the start is 1
            q = deque([(0, 0)])
            while q:
                r, c = q.popleft()
                if (r, c) == (n - 1, n - 1):
                    return dist[(r, c)]
                for dr in (-1, 0, 1):
                    for dc in (-1, 0, 1):           # eight directions
                        x, y = r + dr, c + dc
                        if 0 <= x < n and 0 <= y < n and grid[x][y] == 0 and (x, y) not in dist:
                            dist[(x, y)] = dist[(r, c)] + 1
                            q.append((x, y))
            return -1

    Common mistakes

    • Using only 4 directions.
    • Counting moves instead of cells.

    Similar problems