oneby7

Recursion and Backtracking Searching with constraints

333. Rat in a Maze

Hard

A rat stands in the top-left cell of a square maze, maze, with n rows and n columns. It wants to reach the bottom-right cell. maze[i][j] is 1 if the cell in row i, column j is open, and 0 if it is blocked. The rat can step only onto open cells.

Each move goes one cell down, left, right or up, written 'D', 'L', 'R' and 'U'. A path is the string of moves that takes the rat from the top-left cell to the bottom-right cell without visiting any cell twice. Return every path, sorted in alphabetical order.

If the start or the end is blocked, or no path exists, return an empty list, [].

Example 1

1000111010111111

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

Output: ["DDDRRR","DDDRRURD","DRRDDR","DRRDRD"]

Explanation: Four paths reach the corner. DDDRRURD steps up and around, the other three take six moves. DDDRRR comes before DDDRRURD because the two first differ at the sixth move, and R comes before U.

Example 2

011111111

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

Output: []

Explanation: The rat starts on a blocked cell, so there is no path, even though every other cell is open.

Example 3

1

Input: maze = [[1]]

Output: [""]

Explanation: The start is also the end. The rat is already there, so the one path is the empty string, with no moves.

Check your understanding

Work out the answer for this input before you write any code.

maze = [[1, 1, 1], [1, 1, 1], [0, 1, 1]]

Constraints

  • 1 ≤ n ≤ 5
  • maze.length == maze[i].length == n
  • maze[i][j] is 0 or 1.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.