MediumArrayDepth-First SearchBreadth-First SearchGraphHeap (Priority Queue)MatrixShortest Path

The Maze II

LeetCode
1 approach, code in all languages

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