Ctrl K

Shortest Path of a Rolling Ball

Medium
A maze is given by an m × n grid grid: 0 is an open cell and 1 is a wall. Everything outside the grid counts as a wall too. A ball rests on cell start = [row, col]. You can push it up, down, left or right, and it rolls through open cells until it bumps into a wall. Only once it has stopped can you push it again, in any direction. The length of a route is the number of cells the ball rolls over across all pushes: the cell it starts a push from does not count, the cell where it stops does. Return the shortest length of a route that brings the ball to rest exactly on cell target = [row, col], or -1 if it can never stop there.
Example 1
grid=[[0, 0, 0], [1, 1, 0], [0, 0, 0]], start=[0, 0], target=[2, 0] → 6

Right 2 cells to [0, 2], down 2 to [2, 2], left 2 to [2, 0]: 6 in total.

Example 2
grid=[[0, 0, 1], [0, 0, 0], [1, 0, 0]], start=[0, 0], target=[2, 2] → 4

For example: right 1 to [0, 1] (a wall is next), down 2 to [2, 1], right 1 to [2, 2], for 4 in total. Nothing shorter works.

Example 3
grid=[[0, 0, 0], [0, 0, 0], [0, 0, 0]], start=[0, 0], target=[1, 1] → -1

The ball can never stop in the centre of an empty grid.

Constraints
  • 1 ≤ m, n ≤ 100
  • grid[i][j] is 0 or 1
  • start and target are distinct open cells inside the grid
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBall Into the Hole HardAcross the Hazard Field MediumRepaint Arrows to Reach the Exit HardThrough the Walls to the Far Corner HardRooms on a Timer Hard
loading Python…
Input
grid=[[0, 0, 0], [1, 1, 0], [0, 0, 0]], start=[0, 0], target=[2, 0]
Expected
6

Run checks the first 3 tests in your browser. Submit checks all 58 tests on the server, hidden ones included.