Bootcamps
Masterclasses
Menu
Courses
Account
Login / Sign Up

Rat In A Maze

Hard Acceptance 38% Points 40

Description: A rat is placed at position (0, 0) in an n × n square matrix maze[][]. The goal is to reach the destination (n-1, n-1). Each cell contains:

1 ? free cell (can move)

0 ? blocked cell (cannot move)

The rat can move in four directions:

U (Up), D (Down), L (Left), R (Right)

The rat cannot visit the same cell more than once in a path and can only move inside the grid through free cells.

Return all valid paths in lexicographically sorted order. If no path exists, return an empty list.

Examples
Example 1

Example 1

Input: maze[][] = [ [1, 1], [1, 1] ]

Output: ["DR", "RD"]

Explanation: The rat can reach the destination by moving Down?Right or Right?Down.

Example 2

Example 2

Input: maze[][] = [ [1, 0, 0], [1, 1, 0], [0, 1, 1] ]

Output: ["DRDR"]

Explanation: Only one valid path exists through the open cells.

Example 3

Example 3

Input: maze[][] = [ [1, 0, 0, 0], [1, 1, 0, 1], [1, 1, 0, 0], [0, 1, 1, 1] ]

Output: ["DDRDRR", "DRDDRR"]

Explanation: Multiple valid routes reach the destination; after sorting, both paths are returned.

Constraints
  • 2 = n = 5
  • 0 = maze[i][j] = 1
Topics
Recursion
Companies
Amazon Microsoft Apple Samsung Visa Walmart
Added 19 Jul 2026 38% acceptance
Ln 1, Col 1Sign in to save your code
1
1 0 0
1 1 0
1 1 1
DDRR DRDR