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.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.
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.
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.
grid[i][j] is 0 or 1start and target are distinct open cells inside the gridgrid=[[0, 0, 0], [1, 1, 0], [0, 0, 0]], start=[0, 0], target=[2, 0]
6
Run checks the first 3 tests in your browser. Submit checks all 58 tests on the server, hidden ones included.