AlgoFrames

BFS on a grid with walls

Challenge · Write code · about 25 min

A grid holds 0 for an open cell and 1 for a wall. Starting at the top-left cell, move one step up, down, left or right onto open cells.

Return the fewest steps to reach the bottom-right cell, or -1 if it cannot be reached.

Example 1

Input:

[[[0,0,0],[1,1,0],[0,0,0]]]

Output:

4

Right, right, down, down.

Example 2

Input:

[[[0,1],[1,0]]]

Output:

-1

Walls surround the start.

Constraints

  • 1 ≤ rows, cols ≤ 100
  • Every row has the same length
  • grid[r][c] is 0 or 1

Learn the idea first: Breadth-first search, a visual lesson.

More Breadth-first search problems