KatInterview

Shortest Route Through a Blocked Matrix

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

Last updated

Find the minimum number of unit moves from the top-left to the bottom-right cell of a 0/1 matrix, or report that no route exists.

You are given a rectangular matrix grid with m rows and n columns. Each entry is either 0 (walkable) or 1 (a blocked cell you may not enter). You begin standing on the cell (0, 0) and want to reach the cell (m-1, n-1).

On each step you may move to a cell that shares an edge with your current cell (up, down, left, or right). Diagonal moves are not allowed. Every step costs exactly 1.

Return the total number of steps in a shortest possible route from the start to the destination. If the destination cannot be reached, return -1.

Rules and edge cases to respect:

  • An empty matrix ([]) or a matrix whose first row is empty ([[]]) has no valid start cell: return -1.
  • If the start cell or the destination cell is blocked (1), no route exists: return -1.
  • A 1 x 1 matrix holding [[0]] has start equal to destination: return 0.
  • A 1 x 1 matrix holding [[1]] returns -1.
  • Step counts measure moves, not cells visited. A route through p cells uses p - 1 steps.
  • You may not pass through or land on blocked cells.

Constraints

  • 0 <= m <= 500
  • 0 <= n <= 500
  • Each entry of grid is 0 or 1.
  • When m and n are both positive, every row has exactly n entries.

Examples

Example 1

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

Output: 4

Example 2

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

Output: 5

Example 3

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

Output: -1

Hints

Hint 1

Model each walkable cell as a node and each edge-adjacency between walkable cells as a unit-weight edge; then you need shortest distances in an unweighted graph.

Hint 2

A breadth-first traversal visits cells in increasing order of distance, so the first time you reach a cell you already know the minimum number of moves to it.

Hint 3

Record a cell as visited at the moment you enqueue it rather than when you dequeue it, so that no cell is enqueued twice.