Shortest Path in Binary Matrix

Count the fewest cells a path of zeros needs to cross a square grid from corner to corner, stepping in any of eight directions.

Given an n × n grid of 0s and 1s, return the length of the shortest clear path from the top-left cell to the bottom-right cell. A clear path steps only on cells that hold 0, and each step may go to any of the 8 neighbouring cells, diagonals included. Its length is the number of cells it visits. Return -1 if there is no clear path.

Example 1
Input: grid = [[0,1],[1,0]]
Output: 2
Explanation: one diagonal step from (0,0) to (1,1).
Example 2
Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Output: 4
Example 3
Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
Output: -1
Explanation: the start cell is blocked.
Solution

The Idea

Picture the grid as a floor of square tiles, where 0 is a free tile and 1 is a tile with a box on it. You stand on the top-left tile and want to reach the bottom-right one, stepping only on free tiles. Like a king in chess, you may step onto any of the eight tiles around you, diagonals included.

A cell is named by its row and then its column, both counted from 0, so (0,0) is the top-left cell. Example 2 has three rows and three columns. Row 0 is all free, while columns 0 and 1 of rows 1 and 2 hold boxes. Walking right along row 0 and then down column 2 visits five cells. Cutting the corner, from (0,1) diagonally to (1,2), saves one, and four cells is the answer.

In a 3 × 3 grid the best route can be seen at a glance. In a large grid full of boxes, how can we be sure that no route is shorter than the one we found? Trying every route is hopeless, because the number of routes grows very fast with the size of the grid.

The way out is to sort the free cells by how far they are from the start. The start alone is a path of 1 cell. Every free neighbour of the start can be reached with a path of 2 cells. Every free cell next to those, and not reached yet, needs 3, and so on. Each group of cells reached with the same path length forms a ring around the start. Look at the picture below.

The 3 by 3 grid of Example 2. Each open cell shows its path length: (0,0) is 1, (0,1) is 2, (0,2) and (1,2) are 3, and (2,2) is 4. Rings 1 to 4 list these cells, and the shortest path (0,0), (0,1), (1,2), (2,2) is highlighted.

Each free cell shows the length of the shortest path that reaches it. Ring 1 is the start, (0,0). Ring 2 is (0,1), the only free neighbour of the start. From (0,1) the search reaches (0,2) and, diagonally, (1,2), so both are in ring 3. From (1,2) it reaches the end, (2,2), in ring 4. The orange arrows trace that path of 4 cells.

Why is the ring number the shortest length? A cell joins the first ring that touches it. A shorter path to it would have touched it in an earlier ring, so none exists. Searching like this, finishing every cell at one distance before any cell at the next, is called breadth-first search, or BFS: it goes wide around the start before it goes far.

Solution Approach

Turning the rings into code means settling four things: where the cells of the next ring wait for their turn, how a cell's neighbours are found, how to keep a cell out of two rings, and how to count the length as the rings grow.

A queue for the waiting cells

While the cells of ring 2 are being handled, they discover the cells of ring 3. Where do those wait? In a queue: a line where new items join at the back and are taken from the front, so they come out in the order they went in. The code uses Java's ArrayDeque for it, adding cells at the back with add and taking them from the front with poll. The cells of ring 3 join behind the last cell of ring 2, so a ring is always finished before the next one starts.

Finding the eight neighbours

Seen as a graph, each free cell is a point, and two free cells that touch are joined. Many graph problems keep an adjacency list, a list for each point of the points it is joined to. Here no list is built, because a cell's neighbours follow from its position. Their row and column each differ by at most 1.

So two small loops run a row change dr and a column change dc from -1 to 1. Take (1,2) in Example 2. The changes give (0,1), (0,2), (1,1), (2,1) and (2,2) inside the grid, and the rest fall outside it. Of those five, only (0,1), (0,2) and (2,2) are free. When both changes are 0, the loops give (1,2) itself, which is already marked as reached, so it is skipped too.

Marking cells as reached

In Example 2, (0,1) is a neighbour of both (0,0) and (0,2). How do we stop it from being added again when (0,2) is handled? Each cell is marked as soon as it joins the queue, by writing 1 into it. A 1 already means "do not step here", so the search treats a reached cell like a box, and no separate record of reached cells is needed. The cost is that the method changes the caller's grid. A caller who still needs the grid should pass a copy.

Marking when a cell joins the queue, rather than when it leaves, matters. Otherwise (1,2), a neighbour of both (0,1) and (0,2), could join the queue twice before its turn comes.

Counting the path length

How does the code know where one ring ends? At the start of each ring, the queue holds exactly that ring's cells, so their number is the queue's size at that moment. The code takes out that many cells, and every cell added meanwhile belongs to the next ring. The length starts at 1, for the start cell, and grows by 1 after each ring.

The two corners are checked before the search starts. If the start holds a 1, as in Example 3, or the end holds a 1, no clear path can exist, and the answer is -1 straight away.

Java Solution

The method shortestPathBinaryMatrix works in these steps:

  1. First, store the grid's size in n. If the start grid[0][0] or the end grid[n - 1][n - 1] is not 0, return -1.
  2. Create queue, an ArrayDeque of int[] pairs, each holding a row and a column. Add the start {0, 0}, mark it by setting grid[0][0] to 1, and set length to 1.
  3. While the queue is not empty, handle one ring. Inside that loop, a second loop reads the queue's size into size and takes out exactly that many cells, one at a time, into cell.
  4. If cell is the end, (n - 1, n - 1), return length.
  5. Otherwise, two more loops, one inside the other, run dr and dc from -1 to 1, giving the neighbour's row r and column c. If that neighbour is inside the grid and holds 0, set it to 1 and add it to the queue.
  6. After each ring, add 1 to length. If the queue runs empty without reaching the end, return -1.

The main method prints each grid row by row, then the length: the three examples, a 1 × 1 grid, a grid with a full wall across the middle, and a 5 × 5 grid with a winding path.

Java
import java.util.ArrayDeque;
import java.util.Deque;

public class ShortestPathInBinaryMatrix {

    public static int shortestPathBinaryMatrix(int[][] grid) {
        int n = grid.length;
        if (grid[0][0] != 0 || grid[n - 1][n - 1] != 0) {
            return -1;                                   // a blocked corner: no clear path
        }
        Deque<int[]> queue = new ArrayDeque<>();
        queue.add(new int[] {0, 0});
        grid[0][0] = 1;                                  // 1 now also means "already queued"
        int length = 1;                                  // the start cell alone is a path of 1
        while (!queue.isEmpty()) {
            for (int size = queue.size(); size > 0; size--) {   // one ring of cells
                int[] cell = queue.poll();
                if (cell[0] == n - 1 && cell[1] == n - 1) {
                    return length;
                }
                for (int dr = -1; dr <= 1; dr++) {
                    for (int dc = -1; dc <= 1; dc++) {   // all 8 neighbours
                        int r = cell[0] + dr;
                        int c = cell[1] + dc;
                        if (r >= 0 && r < n && c >= 0 && c < n && grid[r][c] == 0) {
                            grid[r][c] = 1;
                            queue.add(new int[] {r, c});
                        }
                    }
                }
            }
            length++;                                    // the next ring is one cell further
        }
        return -1;                                       // the end was never reached
    }

    static void run(int[][] grid) {
        for (int[] row : grid) {
            StringBuilder line = new StringBuilder();
            for (int v : row) {
                line.append(v).append(' ');
            }
            System.out.println(line.toString().trim());
        }
        System.out.println("length = " + shortestPathBinaryMatrix(grid));
        System.out.println();
    }

    public static void main(String[] args) {
        run(new int[][] {{0, 1}, {1, 0}});
        run(new int[][] {{0, 0, 0}, {1, 1, 0}, {1, 1, 0}});
        run(new int[][] {{1, 0, 0}, {1, 1, 0}, {1, 1, 0}});
        run(new int[][] {{0}});                                   // start is the end
        run(new int[][] {{0, 0, 0}, {1, 1, 1}, {0, 0, 0}});       // a full wall
        run(new int[][] {                                         // a winding path
            {0, 0, 0, 0, 0}, {1, 1, 1, 1, 0}, {0, 0, 0, 0, 0}, {0, 1, 1, 1, 1}, {0, 0, 0, 0, 0}});
    }
}

Running it prints:

Output
0 1
1 0
length = 2

0 0 0
1 1 0
1 1 0
length = 4

1 0 0
1 1 0
1 1 0
length = -1

0
length = 1

0 0 0
1 1 1
0 0 0
length = -1

0 0 0 0 0
1 1 1 1 0
0 0 0 0 0
0 1 1 1 1
0 0 0 0 0
length = 13

The grids are printed before the search, so they show the input, not the 1s the search writes. Example 2 ends with length = 4, the four rings in the picture. The single cell 0 gives length = 1: the start is already the end, and it counts as one cell.

In the grid with 1 1 1 across row 1, both corners are free, yet the result is -1. Diagonal steps cannot slip through a full row of boxes, so the queue runs empty first. The 5 × 5 grid gives 13. Its path runs along row 0 to (0,3), steps diagonally to (1,4) and (2,3), runs left to (2,1), zigzags through (3,0) and (4,1), and runs right to (4,4).

The diagonal steps matter. We ran the same program with one change, allowing only the four steps up, down, left and right. That version prints -1 for Example 1, 5 for Example 2 and 17 for the winding grid.

Complexity

Every free cell joins the queue at most once, and handling it means checking a fixed set of 8 neighbours.

  • Time: O(n2), because each of the n2 cells is added to the queue and taken out at most once, and each time it is taken out the code looks at only 9 positions.
  • Space: O(n2), because the queue holds each cell at most once, so never more than n2 cells, while the grid itself records which cells were reached.

The same ring-by-ring search on a graph of numbered points is Shortest Path in an Unweighted Graph.