Fewest Rolls to Park a Sliding Ball in a Grid
Trees & GraphsAuto-graded · 19 test casesLast 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
originandgoalare the same cell, the answer is0. - 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
gridhasMrows andNcolumns, with1 <= M, N <= 100.- Every entry of
gridis0or1. originandgoalare 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each cell where the ball can come to rest as a node in a graph. From a resting cell, each of the four directions gives at most one outgoing edge, leading to the cell where the ball stops after rolling that way. Every edge costs one roll, so the graph is unweighted and breadth-first search finds the fewest rolls.
To generate the edges, simulate the roll: starting from the current cell, keep stepping in the chosen direction while the next cell is inside the grid and open. The last cell reached is the neighbour. If the ball did not move at all, that direction is skipped, since a zero-length roll is not a move.
The goal counts only if it is the endpoint of a roll, which falls out naturally: we only ever record distances for resting cells. A ball that passes over the goal is never assigned a distance there.
Why it is correct
- The state is exact. Once the ball is at rest, its history does not matter, and it may choose any direction. So the resting cell alone is a complete state, and the four simulated rolls are precisely the legal transitions.
- BFS gives shortest paths in unweighted graphs. Nodes are discovered in non-decreasing distance order, so the first time a cell receives a distance, that distance is minimal. This also allows returning as soon as the goal is discovered.
- Termination and the
-1case. Each cell is enqueued at most once. If the queue empties without discovering the goal, no sequence of rolls ends there, so the answer is-1. - Edge cases.
origin == goalreturns0immediately. A wall goal, or a goal that is only ever passed through, is never a resting cell and yields-1. A ball enclosed on all sides has no valid roll and yields-1.
Complexity
With M rows and N columns:
- Time:
O(M * N * (M + N)). At mostM * Ncells are dequeued, each tries 4 directions, and a roll travels at mostmax(M, N)cells. For a 100 by 100 grid this is about 4 million steps. Precomputing roll endpoints with one sweep per row and column would reduce it toO(M * N). - Space:
O(M * N)for the distance table and the queue.
Reference solution
from collections import deque
from typing import List, Tuple
def fewest_rolls(grid: List[List[int]], origin: Tuple[int, int], goal: Tuple[int, int]) -> int:
rows = len(grid)
cols = len(grid[0])
sr, sc = origin
gr, gc = goal
if (sr, sc) == (gr, gc):
return 0
# dist[r][c] = fewest rolls to rest at (r, c); -1 means not discovered yet
dist = [[-1] * cols for _ in range(rows)]
dist[sr][sc] = 0
queue = deque([(sr, sc)])
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while queue:
r, c = queue.popleft()
for dr, dc in directions:
nr, nc = r, c
moved = False
while True:
rr, cc = nr + dr, nc + dc
if rr < 0 or rr >= rows or cc < 0 or cc >= cols or grid[rr][cc] == 1:
break
nr, nc = rr, cc
moved = True
if moved and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
if (nr, nc) == (gr, gc):
return dist[nr][nc]
queue.append((nr, nc))
return -1