There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall.

When the ball stops, it could choose the next direction to roll. Given the m x n maze, the ball's start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return true if the ball can stop at the destination, otherwise return false.

You may assume that the borders of the maze are all walls.

Input & Output

Example 1 — Path Exists
$ 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
💡 Note: Ball starts at (0,4), rolls down to (4,4), then rolls right to reach destination (4,4)
Example 2 — No Path
$ 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
💡 Note: Ball cannot stop at (3,2) because it's blocked by walls and there's no path that allows stopping there
Example 3 — Start Equals Destination
$ Input: maze = [[0,0,0,0,0],[1,1,0,0,1],[0,0,0,0,0],[0,1,0,0,1],[0,1,0,0,0]], start = [0,0], destination = [0,0]
Output: true
💡 Note: Ball is already at destination, so return true immediately

Constraints

  • m == maze.length
  • n == maze[i].length
  • 1 ≤ m, n ≤ 100
  • maze[i][j] is 0 or 1
  • start.length == 2
  • destination.length == 2
  • 0 ≤ startrow, destinationrow < m
  • 0 ≤ startcol, destinationcol < n
  • Both the ball and the destination exist in an empty space, and they will not be in the same position initially
  • The maze contains at least 2 empty spaces

Visualization

Tap to expand
The Maze - DFS with Visited Set INPUT 0 0 1 0 S 0 0 0 0 0 0 0 0 1 0 1 1 0 1 1 0 0 0 0 D Start [0,4] Dest [4,4] Wall (1) Empty (0) start = [0, 4] destination = [4, 4] maze: 5x5 grid ALGORITHM STEPS 1 Initialize DFS Create visited set, start from position [0,4] 2 Roll Ball Roll in one direction until hitting a wall 3 Check & Mark If at dest, return true Mark stop as visited 4 Recurse Try all 4 directions from current stop Path Found: [0,4]-->[4,4] via [1,4] S D FINAL RESULT Output: true Ball can reach destination! Ball rolls from [0,4] down to [4,4] and stops OK - Path exists! Key Insight: The ball keeps rolling until it hits a wall - it cannot stop in the middle of empty spaces. DFS explores all possible stopping positions. The visited set prevents revisiting the same stop position, ensuring O(m*n) time complexity. Each cell is visited at most once as a stop point. TutorialsPoint - The Maze | DFS with Visited Set Approach
Asked in
Google 42 Facebook 38 Amazon 35 Microsoft 28
89.2K Views
Medium Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen