Shortest Path in Binary Matrix

Medium

Topics
GraphBFSMatrix

Given a binary matrix grid, return the length of the shortest clear path from the top-left cell to the bottom-right cell, or -1 if none exists. A clear path visits only cells with value 0 and may move in any of the 8 directions. Path length is the number of visited cells.

Example 1

00111001
a shortest pathblocked
Steps may go in all eight directions, which is what makes this shorter than a normal grid walk. The answer counts cells on the path, not moves, so the shaded route of 2 cells is the answer.
2D grid — one row per line.
Input:  grid = [[0,1],[1,0]]
Output: 2

Example 2

000011102110012
a shortest pathblocked
Input:  grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4

Constraints

  • 1 <= m, n <= 100
  • grid[i][j] is 0 or 1.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every move costs the same one cell, so the shortest path is a breadth-first search — no weights, no priority queue, no Dijkstra. The only twists are that movement is 8-directional rather than 4, and that the answer counts cells visited rather than steps taken, so the start cell already counts as 1.

Expanding level by level means the distance is the level index, which removes the need to store a distance per cell. Mark a cell visited when it is queued, not when it is dequeued — otherwise the same cell is reached from up to eight neighbours and enters the queue repeatedly. On a 100×100 open grid that is the difference between queueing 9,999 cells and queueing 39,402.

Approach

  1. Reject immediately if either corner is blocked.
  2. Seed the frontier with the top-left cell, marked visited, at length 1.
  3. For each cell in the current frontier, return the current length if it is the bottom-right cell.
  4. Otherwise queue every unvisited open neighbour among the 8 directions, marking each as it is queued.
  5. Increment the length and repeat with the new frontier. An empty frontier means no path, so return -1.

Dry Run

grid          0 0 0
              1 1 0
              1 1 0

  layer  cells at this distance
  1      (0,0)
  2      (0,1)
  3      (0,2) (1,2)
  4      (2,2)   <- bottom-right reached

answer 4

  [[0,1],[1,0]]              -> 2    the diagonal is a legal move
  [[1,0,0],[1,1,0],[1,1,0]]  -> -1   start is blocked
  [[0]]                      -> 1    a single open cell is a path of one cell
  [[0,0],[1,1]]              -> -1   no route to the corner

Complexity

  • Time — O(m·n): each cell is marked once and its 8 neighbours are examined once.
  • Space — O(m·n) for the visited grid and the frontier. Reusing a copy of the input as the visited marker avoids a second allocation; mutating the caller's grid avoids even that, at the cost of a side effect worth mentioning out loud.

Common Pitfalls

  • Marking cells visited on dequeue rather than on enqueue. With 8 neighbours the same cell is queued many times over; measured on a 100×100 open grid, the queue takes 39,402 entries instead of 9,999. The answer stays correct, so this is a silent 4× cost.
  • Using depth-first search. DFS finds a path, not the shortest one, and on a grid it typically finds a terrible one.
  • Reaching for Dijkstra or A*. Every edge has weight 1, which is precisely the condition under which BFS already gives the optimum; A* with a Chebyshev-distance heuristic is a legitimate speedup to mention, but plain BFS is the expected answer.
  • Counting steps instead of cells, which is off by one: a single open cell answers 1, not 0.
  • Only checking 4 directions, or writing the 8 offsets by hand and omitting one. Deriving them as all (dr, dc) with dr, dc in {-1,0,1} excluding (0,0) is harder to get wrong.
  • Forgetting to test the destination when the grid is a single cell, where start and end coincide and the loop must return on the very first frontier.

Full Solution — all languages

class Solution:
    def shortestPathBinaryMatrix(self, grid):
        R, C = len(grid), len(grid[0])
        if grid[0][0] != 0 or grid[R-1][C-1] != 0:
            return -1
        dirs = [(1,0),(-1,0),(0,1),(0,-1),(1,1),(1,-1),(-1,1),(-1,-1)]
        vis = [row[:] for row in grid]
        vis[0][0] = 1
        q = [(0, 0)]
        length = 1
        while q:
            nq = []
            for r, c in q:
                if r == R-1 and c == C-1:
                    return length
                for dr, dc in dirs:
                    nr, nc = r+dr, c+dc
                    if 0 <= nr < R and 0 <= nc < C and vis[nr][nc] == 0:
                        vis[nr][nc] = 1
                        nq.append((nr, nc))
            length += 1
            q = nq
        return -1
SensAI
Beta
Tap the mic to stop voice mode