MediumArrayDepth-First SearchBreadth-First SearchMatrix
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now