Rat in a Maze - Problem

A rat is placed at position (0, 0) in an N x N maze. The rat needs to find all possible paths to reach the destination at (N-1, N-1).

The rat can only move in two directions:

  • Right (R): from (i, j) to (i, j+1)
  • Down (D): from (i, j) to (i+1, j)

The maze is represented by a 2D array where 1 indicates an open path and 0 indicates a blocked wall. The rat can only move through cells containing 1.

Return all possible paths as a list of strings, where each string represents a path using characters 'R' (right) and 'D' (down). If no path exists, return an empty list.

Input & Output

Example 1 — Basic 3x3 Maze
$ Input: maze = [[1,1,1],[1,0,1],[1,1,1]]
Output: ["RRDD","RDRD","DRRD","DDRR"]
💡 Note: Four valid paths exist: going right-right-down-down, right-down-right-down, down-right-right-down, and down-down-right-right. The middle cell (1,1) is blocked.
Example 2 — Single Path
$ Input: maze = [[1,0],[1,1]]
Output: ["DR"]
💡 Note: Only one path possible: down from (0,0) to (1,0), then right to destination (1,1). Cannot go right first due to blocked cell.
Example 3 — No Path Available
$ Input: maze = [[1,0],[0,1]]
Output: []
💡 Note: No path exists because both adjacent cells from start (0,0) are blocked, making destination unreachable.

Constraints

  • 1 ≤ maze.length ≤ 10
  • maze[i][j] is 0 or 1
  • maze[0][0] = 1 (start is always open)

Visualization

Tap to expand
INPUT MAZEBACKTRACKINGRESULTS1110111E3x3 maze with blocked centerStart: (0,0) → End: (2,2)1234Try R&DRecurseMark pathBacktrackAll Valid Paths:"RRDD""RDRD""DRRD""DDRR"4 paths foundKey Insight:Backtracking systematically explores all valid paths by trying each direction,marking visited cells, and cleaning up to allow alternate routes through the same cells.TutorialsPoint - Rat in a Maze | Backtracking Algorithm
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
34.5K Views
Medium Frequency
~25 min Avg. Time
890 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