FunctionRacerProblemsRace

Roll Until It Stops

HardGridsPython, JavaScript, TypeScript, Java, C++

grid is a board, one string per row: . is open and # is a wall. A ball lies on the cell start, given as [row, column].

You tilt the board up, down, left or right. The ball then rolls that way and does not stop until the next cell is a wall or the edge of the board. Only then can you tilt again.

Return the fewest cells the ball must travel in total to come to rest on goal, or -1 if it can never stop there. Rolling over goal without stopping does not count.

Example 1

grid ["....",".#..","...."]
start [0,0]
goal [2,3]
returns 5

Roll right for 3 cells, then down for 2. Down first and then right is just as long.

Example 2

grid ["....."]
start [0,0]
goal [0,2]
returns -1

The ball always rolls on to an end of the row. It never rests in the middle.

Example 3

grid ["..#","...","#.."]
start [1,1]
goal [1,1]
returns 0

The ball is already there.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Grids problems