1 approach, code in every language
Problem description
A ball is placed in a maze represented by an m x n grid. Each cell is either empty, written as 0, or a wall, written as 1.
The ball can roll up, down, left, or right, but once it starts rolling in a direction it does not stop until it strikes a wall. Only after stopping can it choose a new direction.
Given the ball's start position and a destination position (each given as [row, column]), determine whether the ball can come to rest exactly at the destination. Return true if it can, and false otherwise. You may assume the borders of the maze are all walls, and that the start and destination are distinct empty cells.
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: true
One route is down, then left, then down; the ball comes to rest exactly on the destination.
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: false
The ball can never stop at [3, 2]; whenever it rolls through that cell it keeps going until a wall stops it elsewhere.
Constraints
m == maze.lengthn == maze[i].length1 <= m, n <= 100maze[i][j] is 0 or 1start.length == 2 and destination.length == 20 <= startRow, destinationRow < m0 <= startCol, destinationCol < nBoth the ball and the destination sit on empty cells, and they are differentThe maze contains at least two 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