KatInterview

Fewest Rolls to Park a Sliding Ball in a Grid

Trees & GraphsAuto-graded · 19 test cases
MediumAuto-gradedTrees & Graphsbfsgridgraph

Last updated

Model a sliding ball as BFS over resting positions, where each edge is a full roll until a wall or border, and the target counts only if the ball stops on it.

Sliding Ball Puzzle

You are given a rectangular grid grid in which 0 marks an open cell and 1 marks a wall. A ball rests at the cell origin = (row, col). Your goal is to get it to rest at the cell goal = (row, col).

On each move you choose one of four directions: up, down, left or right. The ball then rolls in that direction without stopping, passing from one open cell to the next, until the next cell in that direction is either a wall or outside the grid. The ball comes to rest on the last open cell it reached. Only once it has come to rest can it pick a new direction.

Return the minimum number of rolls needed so that the ball comes to rest on goal. If this is impossible, return -1.

Rules

  • Every roll that ends on a different cell counts as exactly one roll. A direction whose first neighbouring cell is blocked produces no movement and is not a roll.
  • The goal is reached only when the ball stops on it. Rolling over the goal cell and continuing does not count.
  • If origin and goal are the same cell, the answer is 0.
  • The ball may revisit cells it has already rested on, but this never helps a shortest answer.

Function

Implement fewest_rolls(grid, origin, goal) returning the integer described above.

Constraints

  • grid has M rows and N columns, with 1 <= M, N <= 100.
  • Every entry of grid is 0 or 1.
  • origin and goal are valid coordinates inside the grid, given as (row, col) pairs (lists of two integers are also accepted).
  • The ball must come to a complete stop before changing direction.

Examples

Example 1

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

Output: 4

Example 2

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

Output: -1

Hints

Hint 1

Think about which positions matter as graph nodes: only cells where the ball can come to rest, not every cell it passes through.

Hint 2

From a resting cell, each of the four directions leads to at most one new resting cell. Simulate the roll with a loop that advances until the next cell is a wall or out of bounds.

Hint 3

Every roll costs one, so the graph is unweighted and breadth-first search gives the minimum. Remember to ignore zero-length rolls and to count the goal only when it is an endpoint of a roll.