Shortest Path in Binary Matrix solution explained

To find the shortest clear path in a binary matrix, run a breadth-first search from the top-left cell over open cells (value 0), allowing all eight moves including diagonals, and return the distance when the bottom-right cell is reached. Count the path in cells, so the start has distance 1, and return -1 if either corner is blocked or the search runs out of cells. Each cell is visited at most once with eight neighbour checks, so the search is O(n²) for an n by n grid.

By Published 7 min read

The task, restated

You are given an n by n grid where 0 is an open cell and 1 is a wall. Find the shortest path from the top-left cell to the bottom-right cell that only passes through open cells. From any cell you may step to any of its eight neighbours: up, down, left, right or diagonally. The length of a path is the number of cells on it, including both ends. Return that length, or -1 if no such path exists.

Grids made up for this page (rows separated by slashes)
GridAnswerPath
0 1 1 / 1 0 1 / 1 1 03Straight down the diagonal.
0 0 0 / 1 1 0 / 1 1 04Right, then diagonally down-right, then down.
01The start is the end.
1-1The only cell is a wall.
0 1 / 1 1-1The bottom-right cell is a wall.
Grids made up for this page (rows separated by slashes). Scroll sideways on a small screen.

What the interviewer is looking for

This is a direct test of whether you reach for BFS when a question asks for the fewest steps with equal-cost moves. The interviewer will also watch for three small things: the eight directions (many candidates write four out of habit), the length counted in cells rather than moves, and the corner checks. A good answer mentions that DFS would explore paths in the wrong order and could only find the shortest by trying all of them.

Why not DFS

A depth-first search follows one path as far as it goes before trying another. It will find a path if one exists, but the first one it finds may be long and winding. To get the shortest, it would have to try every simple path and keep the best, and the number of simple paths in a grid grows exponentially. That exhaustive search is useful only as a test reference on tiny grids, which is how the code on this page was checked.

BFS over the grid

BFS explores cells in order of distance from the start: first the start, then everything one step away, then two steps, and so on. So the first time it reaches the target, it has done so by a shortest path. Store each cell's distance in a grid, using 0 to mean unreached, set the start to 1, and give every newly reached neighbour its parent's distance plus one.

from collections import deque


def shortest_clear_path(grid):
    n = len(grid)
    if grid[0][0] or grid[n - 1][n - 1]:
        return -1
    steps = [(dr, dc) for dr in (-1, 0, 1) for dc in (-1, 0, 1) if dr or dc]
    dist = [[0] * n for _ in range(n)]    # 0 = not reached; otherwise cells on the path
    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, dc in steps:
            nr, nc = r + dr, c + dc
            if 0 <= nr < n and 0 <= nc < n and grid[nr][nc] == 0 and dist[nr][nc] == 0:
                dist[nr][nc] = dist[r][c] + 1     # mark on enqueue
                queue.append((nr, nc))
    return -1
BFS with a distance grid. O(n²) time and space.

Trace the second grid. The start (0, 0) has distance 1. Its open neighbour (0, 1) gets 2. From (0, 1), the open neighbours are (0, 2) and, diagonally, (1, 2), both distance 3. From (1, 2), the target (2, 2) gets 4, and when it comes off the queue the function returns 4.

function shortestClearPath(grid) {
  const n = grid.length;
  if (grid[0][0] === 1 || grid[n - 1][n - 1] === 1) return -1;
  const dist = Array.from({ length: n }, () => new Array(n).fill(0));
  dist[0][0] = 1;
  let frontier = [[0, 0]];
  while (frontier.length > 0) {          // one BFS layer per loop
    const next = [];
    for (const [r, c] of frontier) {
      if (r === n - 1 && c === n - 1) return dist[r][c];
      for (let dr = -1; dr <= 1; dr++) {
        for (let dc = -1; dc <= 1; dc++) {
          const nr = r + dr;
          const nc = c + dc;
          if (nr < 0 || nc < 0 || nr >= n || nc >= n) continue;
          if (grid[nr][nc] === 1 || dist[nr][nc] !== 0) continue;
          dist[nr][nc] = dist[r][c] + 1;
          next.push([nr, nc]);
        }
      }
    }
    frontier = next;
  }
  return -1;
}
Layer by layer: each loop builds the next frontier.

Processing a whole layer at a time avoids a queue class in JavaScript and makes the distance easy to see, since every cell in a frontier has the same distance. The double loop over dr and dc includes (0, 0), which is harmless because the current cell is already marked.

A faster search in practice: A*

If the interviewer pushes for speed on large open grids, mention A*. It orders cells by distance so far plus an estimate of the distance left. With diagonal moves allowed and every move costing one, the larger of the row gap and the column gap to the target never overestimates the remaining moves, so A* still returns a shortest path while often exploring fewer cells. Its worst case is no better than BFS, and it needs a priority queue, so BFS is the expected answer.

Complexity

n by n grid
ApproachTimeExtra space
Try every simple path (DFS)ExponentialO(n²) for the path
BFSO(n²), with 8 checks per cellO(n²) for distances and the queue
A* with the max-gap estimateO(n² log n) worst case with a heapO(n²)
n by n grid. Scroll sideways on a small screen.

Edge cases

  • A blocked start or a blocked target: -1 before searching.
  • A 1 by 1 grid with a 0: the answer is 1.
  • A path that only exists through a diagonal gap between two walls.
  • A grid with no walls: the answer is n, straight along the diagonal.
  • A wall line that cuts the grid in two: the queue empties and the answer is -1.

Mistakes

  • Using four directions instead of eight.
  • Returning the number of moves instead of the number of cells.
  • Checking only the start corner and not the target.
  • Marking cells as visited when they are dequeued, so the same cell is queued from several neighbours.
  • Modifying the input grid to mark visits without saying so; it is a common trick, but mention it.
  • Using DFS and returning the first path found.

How to explain it out loud

Fictional example

Choosing BFS and stating the counts
Candidate
Every move costs the same, one cell, so the shortest path is a BFS distance. I'll allow all eight directions.
Candidate
If the top-left or bottom-right cell is a wall, I return minus one straight away. Otherwise the start has distance one, since we count cells.
Interviewer
And when do you mark a cell?
Candidate
When I push it, so it can't be queued twice. Each cell is handled once with eight checks, so it's n squared time and n squared space for the distances.

Open the Lock runs the same BFS on codes instead of cells, and Snakes and Ladders on board squares. When moves have different costs, or the cost is the highest cell on the path, see Swim in Rising Water. For grid DFS without distances, Number of Islands is the classic, and Word Break II moves from grids to strings.

Rehearsing it with Natively

Grid BFS questions are mostly about getting small details right. Natively can read the grid problem from a screenshot on Mac or Windows and set out an approach and code in its overlay, which you can compare with your direction list and corner checks. During a spoken mock, it transcribes the conversation so you can confirm later that you said why BFS and not DFS. Details on the AI interview assistant.

Questions people ask

How do you solve Shortest Path in Binary Matrix?

Run a BFS from the top-left cell over cells with value 0, allowing all eight moves, and return the distance in cells when the bottom-right cell is reached. Return -1 if a corner is blocked or the queue empties.

Why use BFS instead of DFS for Shortest Path in Binary Matrix?

BFS explores cells in order of distance, so the first time it reaches the target it has a shortest path. DFS can find a long path first.

Does Shortest Path in Binary Matrix count cells or moves?

Cells. The start counts as 1, so an open 1 by 1 grid returns 1.

What is the time complexity of Shortest Path in Binary Matrix?

O(n²) for an n by n grid, since each cell is queued at most once and checks eight neighbours. Space is also O(n²).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP