KatInterview

Fewest Moves Through a Walled Maze

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbfsgridshortest-path

Last updated

Compute the minimum number of 4-directional moves between two open cells of a binary maze, or -1 if unreachable; tests breadth-first search on an implicit grid graph.

Fewest Moves Through a Walled Maze

A maze is given as a rectangular grid of integers. A cell containing 0 is open floor, and a cell containing 1 is a wall.

You begin on one open cell and want to reach another open cell. In a single move you may step onto any of the four orthogonally adjacent cells (up, down, left, right). You may never leave the grid, and you may never step onto a wall.

Return the minimum number of moves needed to get from the starting cell to the target cell. If the target cannot be reached, return -1.

Function inputs

  • grid: a list of m rows, each a list of n integers (0 or 1).
  • start: a two-element list [row, col] giving the starting cell.
  • end: a two-element list [row, col] giving the target cell.

Output

An integer: the minimum number of moves, or -1 if no route exists. If start and end are the same cell, the answer is 0.

Constraints

  • 1 <= m, n <= 1000
  • Every row of grid has the same length n.
  • Each entry of grid is 0 or 1.
  • 0 <= start[0], end[0] < m and 0 <= start[1], end[1] < n.
  • grid[start[0]][start[1]] == 0 and grid[end[0]][end[1]] == 0.
  • The solution should run fast enough for grids with up to 10^6 cells.

Examples

Example 1

Input: fewest_moves([[0, 0, 0], [1, 1, 0], [0, 0, 0]], [0, 0], [2, 2])

Output: 4

Example 2

Input: fewest_moves([[0, 1], [1, 0]], [0, 0], [1, 1])

Output: -1

Example 3

Input: fewest_moves([[0, 0, 0], [0, 0, 0]], [0, 0], [1, 2])

Output: 3

Hints

Hint 1

Think of every open cell as a node in a graph, with an edge between each pair of adjacent open cells. Every edge costs exactly one move.

Hint 2

When all edges cost the same, a search that expands outward level by level reaches each cell by a shortest route the first time it sees it. Which traversal does that?

Hint 3

Mark a cell as seen at the moment you add it to the queue, not when you remove it, and handle start == end up front. Use a deque so removing from the front is O(1).