Recursion and Backtracking Searching with constraints
333. Rat in a Maze
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
Input: maze = [[1, 0, 0, 0],
[1, 1, 1, 0],
[1, 0, 1, 1],
[1, 1, 1, 1]]
["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
Input: maze = [[0, 1, 1], [1, 1, 1], [1, 1, 1]]
[]Explanation: The rat starts on a blocked cell, so there is no path, even though every other cell is open.
Example 3
Input: maze = [[1]]
[""]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.
Constraints
1 ≤ n ≤ 5maze.length == maze[i].length == nmaze[i][j]is0or1.
Clarifying questions
What you would ask an interviewer before writing any code.