KatInterview

Minimum Steps Through an Obstacle Map

Trees & GraphsAuto-graded · 21 test cases
MediumAuto-gradedTrees & Graphsbfsgraphsgrid

Last updated

Tests ability to model a 2D grid as an unweighted graph and apply BFS to find the fewest moves between two corners while avoiding walls.

Minimum Steps Through an Obstacle Map

You have a map represented as an m x n binary grid. Each cell holds either 0 (open ground) or 1 (a wall). You begin at the top-left cell (0, 0) and want to reach the bottom-right cell (m - 1, n - 1).

Each move travels to an adjacent cell in one of the four cardinal directions: up, down, left, or right. You may only enter cells that contain 0.

Write a function min_steps_through_map(grid) that returns the minimum number of moves needed to travel from the start to the destination. If no such route exists, return -1.

Constraints

  • 1 <= m, n <= 200 where m is the number of rows and n is the number of columns.
  • Every cell is either 0 or 1.
  • grid[0][0] and grid[m-1][n-1] are always 0.
  • Diagonal moves are not allowed.

Examples

Example 1

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

Output: 4

Example 2

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

Output: -1

Hints

Hint 1

Think about what search strategy guarantees the fewest moves in a graph where every edge has the same cost. Which classic traversal explores neighbors layer by layer, nearest first?

Hint 2

Keep a separate structure to record which cells have already been discovered. Record a cell's distance from the start the moment you add it to the queue — not when you pull it out — to avoid adding the same cell more than once.

Hint 3

If the queue empties before you reach the bottom-right corner, no open path connects the two corners. What should your function return in that case?