The Maze II
1 approach, code in every language
Problem description
A ball is placed in a maze given as a grid `maze`, where `0` marks an empty cell and `1` marks a wall. When the ball starts rolling in a chosen direction, it keeps moving until it collides with a wall (or the maze border) and only then can it pick a new direction.
Given the ball's `start` position and a `destination` cell, return the shortest distance the ball travels to stop exactly at the destination, where distance counts the number of empty cells passed through (excluding the starting cell but including the cell it stops on).
If the ball can never come to rest on the destination cell, return `-1`.
Example 1
Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [4,4]
Output: 12
One shortest route rolls left, down, left, down and stops on the destination after crossing 12 empty cells in total.
Example 2
Input: maze = [[0,0,1,0,0],[0,0,0,0,0],[0,0,0,1,0],[1,1,0,1,1],[0,0,0,0,0]], start = [0,4], destination = [3,2]
Output: -1
Every roll passes over [3,2] without ever stopping on it, so the ball cannot rest at that cell and the answer is -1.
Constraints
m == maze.lengthn == maze[i].length1 <= m, n <= 100maze[i][j] is 0 or 1.start.length == 2 and destination.length == 20 <= start[0], destination[0] < m0 <= start[1], destination[1] < nBoth the ball and the destination sit on empty cells and are not at the same position.The maze contains at least 2 empty cells.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free