Maze Solver - Problem

Given a 2D grid representing a maze where 0 represents an open path and 1 represents a wall, find a path from the top-left corner (0,0) to the bottom-right corner (rows-1, cols-1).

If a valid path exists, return the path as a list of coordinates in the format [[row1,col1], [row2,col2], ...]. If no path exists, return an empty list [].

Movement Rules: You can only move in 4 directions: up, down, left, right (no diagonal movement).

Input & Output

Example 1 — Basic 3x3 Maze
$ Input: maze = [[0,1,0],[0,0,0],[1,0,0]]
Output: [[0,0],[1,0],[2,0],[2,1],[2,2]]
💡 Note: Path goes down from (0,0) to (1,0) to (2,0), then right to (2,1) and finally (2,2). Cannot go through walls (1s).
Example 2 — Blocked Path
$ Input: maze = [[0,1,0],[1,1,0],[0,0,0]]
Output: []
💡 Note: No valid path exists from top-left to bottom-right due to walls blocking all possible routes.
Example 3 — Single Cell
$ Input: maze = [[0]]
Output: [[0,0]]
💡 Note: Single open cell - start and end are the same position, so path contains just that coordinate.

Constraints

  • 1 ≤ maze.length, maze[i].length ≤ 100
  • maze[i][j] is 0 or 1
  • maze[0][0] and maze[m-1][n-1] are guaranteed to be 0

Visualization

Tap to expand
INPUT MAZEBACKTRACKING SEARCHPATH RESULTS1000010EGrid: 0=open, 1=wallStart: (0,0) End: (2,2)1Start at (0,0)2Try all 4 directions3Mark visited, recurse4Backtrack on dead end5Return path when foundPath Coordinates:[(0,0), (1,0), (2,0), (2,1), (2,2)]Valid path found fromstart to destinationavoiding all wallsKey Insight:Backtracking with visited tracking prevents infinite loops and systematicallyexplores all possible paths until a valid route to the destination is discovered.TutorialsPoint - Maze Solver | DFS Backtracking Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Facebook 18
28.5K Views
Medium Frequency
~25 min Avg. Time
850 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