MediumArrayDepth-First SearchBreadth-First SearchMatrix

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.length
  • n == maze[i].length
  • 1 <= m, n <= 100
  • maze[i][j] is 0 or 1
  • start.length == 2 and destination.length == 2
  • 0 <= startRow, destinationRow < m
  • 0 <= startCol, destinationCol < n
  • Both the ball and the destination sit on empty cells, and they are different
  • The maze contains at least two empty cells

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