← Back to Algorithms, page 4

algorithms-0076 · Medium fresher

Shortest path in a binary grid: find the fewest cells on a clear path from the top-left to the bottom-right corner, moving in all eight directions.

Each 0-cell is a node connected to its up to eight 0-neighbours, and every move costs 1, so BFS from the top-left gives shortest distances. Return -1 early if either corner is blocked. Store distances in a grid and mark cells when they are enqueued. Time and space are O(R * C).

Full answer

Problem

Given an R x C grid of 0 (open) and 1 (blocked), return the number of cells on the shortest path from (0, 0) to (R-1, C-1) that moves through open cells in any of the 8 directions, or -1 if no path exists.

Example: [[0,1],[1,0]] returns 2 (diagonal step). [[0,0,0],[1,1,0],[1,1,0]] returns 4. A blocked start returns -1.

Constraints: 1 <= R, C <= 100.

Brute force

DFS over all simple paths and keep the shortest: exponential. Repeated relaxation (update every cell from its neighbours until nothing changes) is correct but can take O((R * C)^2).

Optimal approach

  1. If the start or end is blocked, return -1.
  2. dist[0][0] = 1; queue [(0, 0)].
  3. Pop a cell; if it is the target, return its distance. For each of the 8 neighbours inside the grid that is open and unvisited (dist == 0), set dist = dist + 1 and enqueue.
  4. If the queue empties, return -1.

Why it works

All moves have equal cost, so BFS visits cells in order of path length; the first time the target is popped, its distance is the shortest. Using the distance grid as the visited marker ensures each cell is enqueued once.

Complexity

O(R * C) time (each cell processed once with 8 neighbour checks) and O(R * C) space.

Code

python
import random
from collections import deque


def shortest_path_binary_matrix(grid):
    """Length (in cells) of the shortest clear path from top-left to bottom-right,
    moving in 8 directions through 0-cells. -1 if none. BFS: O(R * C)."""
    n, m = len(grid), len(grid[0])
    if grid[0][0] or grid[n - 1][m - 1]:
        return -1
    dist = [[0] * m for _ in range(n)]
    dist[0][0] = 1
    q = deque([(0, 0)])
    while q:
        r, c = q.popleft()
        if (r, c) == (n - 1, m - 1):
            return dist[r][c]
        for dr in (-1, 0, 1):
            for dc in (-1, 0, 1):
                nr, nc = r + dr, c + dc
                if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 0 and dist[nr][nc] == 0:
                    dist[nr][nc] = dist[r][c] + 1
                    q.append((nr, nc))
    return -1


def brute(grid):
    """Repeated relaxation until nothing changes (slow but obviously correct)."""
    n, m = len(grid), len(grid[0])
    INF = float("inf")
    d = [[INF] * m for _ in range(n)]
    if grid[0][0] == 0:
        d[0][0] = 1
    changed = True
    while changed:
        changed = False
        for r in range(n):
            for c in range(m):
                if grid[r][c] or d[r][c] == INF:
                    continue
                for dr in (-1, 0, 1):
                    for dc in (-1, 0, 1):
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 0 and d[r][c] + 1 < d[nr][nc]:
                            d[nr][nc] = d[r][c] + 1
                            changed = True
    return -1 if d[-1][-1] == INF else d[-1][-1]


if __name__ == "__main__":
    assert shortest_path_binary_matrix([[0, 1], [1, 0]]) == 2
    assert shortest_path_binary_matrix([[0, 0, 0], [1, 1, 0], [1, 1, 0]]) == 4
    assert shortest_path_binary_matrix([[1, 0, 0], [1, 1, 0], [1, 1, 0]]) == -1
    assert shortest_path_binary_matrix([[0]]) == 1
    rng = random.Random(76)
    for _ in range(500):
        n, m = rng.randint(1, 6), rng.randint(1, 6)
        g = [[int(rng.random() < 0.3) for _ in range(m)] for _ in range(n)]
        assert shortest_path_binary_matrix(g) == brute(g)
    print("all tests passed")

Save as b76_grid_shortest_path.py and run python3 b76_grid_shortest_path.py. It prints all tests passed (Python 3.13.5).

Edge cases

1 x 1 grid with an open cell (answer 1). Start or end blocked. Single row or column. Counting cells versus steps (this problem counts cells, so the start contributes 1).

Pattern

BFS on an implicit grid graph. Changing the neighbour set or costs gives related problems: 4-direction mazes, knight moves on a board, multi-source BFS (nearest gate, rotting oranges), 0-1 BFS when some moves are free, and A* with a Chebyshev distance heuristic for large open grids.

python
import random
from collections import deque


def shortest_path_binary_matrix(grid):
    """Length (in cells) of the shortest clear path from top-left to bottom-right,
    moving in 8 directions through 0-cells. -1 if none. BFS: O(R * C)."""
    n, m = len(grid), len(grid[0])
    if grid[0][0] or grid[n - 1][m - 1]:
        return -1
    dist = [[0] * m for _ in range(n)]
    dist[0][0] = 1
    q = deque([(0, 0)])
    while q:
        r, c = q.popleft()
        if (r, c) == (n - 1, m - 1):
            return dist[r][c]
        for dr in (-1, 0, 1):
            for dc in (-1, 0, 1):
                nr, nc = r + dr, c + dc
                if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 0 and dist[nr][nc] == 0:
                    dist[nr][nc] = dist[r][c] + 1
                    q.append((nr, nc))
    return -1


def brute(grid):
    """Repeated relaxation until nothing changes (slow but obviously correct)."""
    n, m = len(grid), len(grid[0])
    INF = float("inf")
    d = [[INF] * m for _ in range(n)]
    if grid[0][0] == 0:
        d[0][0] = 1
    changed = True
    while changed:
        changed = False
        for r in range(n):
            for c in range(m):
                if grid[r][c] or d[r][c] == INF:
                    continue
                for dr in (-1, 0, 1):
                    for dc in (-1, 0, 1):
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < n and 0 <= nc < m and grid[nr][nc] == 0 and d[r][c] + 1 < d[nr][nc]:
                            d[nr][nc] = d[r][c] + 1
                            changed = True
    return -1 if d[-1][-1] == INF else d[-1][-1]


if __name__ == "__main__":
    assert shortest_path_binary_matrix([[0, 1], [1, 0]]) == 2
    assert shortest_path_binary_matrix([[0, 0, 0], [1, 1, 0], [1, 1, 0]]) == 4
    assert shortest_path_binary_matrix([[1, 0, 0], [1, 1, 0], [1, 1, 0]]) == -1
    assert shortest_path_binary_matrix([[0]]) == 1
    rng = random.Random(76)
    for _ in range(500):
        n, m = rng.randint(1, 6), rng.randint(1, 6)
        g = [[int(rng.random() < 0.3) for _ in range(m)] for _ in range(n)]
        assert shortest_path_binary_matrix(g) == brute(g)
    print("all tests passed")

8-direction BFS with a distance grid, cross-checked against repeated relaxation on random grids.

Complexity

Time: O(R * C). Space: O(R * C). A* with the Chebyshev heuristic explores fewer cells on open grids but has the same worst case.

By level

Fresher: Models the grid as a graph and runs BFS with 8 neighbour offsets. Handles blocked corners and counts cells correctly.

Mid: Explains why BFS order guarantees the shortest path and reconstructs the path with parents. Adapts to weighted cells with Dijkstra.

Senior: Discusses A* heuristics, bidirectional search for large maps, and precomputation for repeated queries on static maps. Considers memory use for very large grids.

Key points

  • Grid cells are nodes, moves are unit edges
  • BFS gives shortest paths for unit costs
  • Check blocked corners first
  • Use the distance grid as visited
  • Count cells or steps as the problem says

Common mistakes

  • Using DFS for shortest paths
  • Forgetting diagonal moves
  • Off-by-one between cells and steps
  • Marking visited on dequeue and enqueueing cells many times

Follow-ups

  • How would A* speed this up?
  • How do you return the path itself?
  • What changes if some cells cost more to enter?

Tips

  • Clarify allowed moves
  • State why BFS is correct here
  • Handle blocked corners before searching

Evaluation rubric

  • Correct BFS
  • Correct neighbour set
  • Correct edge cases
  • Correct complexity