Menu
CoddyTech

Rat in a Maze

MediumBacktrackingpython iconjava iconcpp iconc iconjs icon+10

A rat starts in the top left cell of an n × n maze, where 1 is an open cell and 0 a wall, and must reach the bottom right cell. Each move goes one cell down (D), left (L), right (R) or up (U) onto an open cell. A path never visits a cell twice and ends at the exit.

Return every path as a string of moves, in alphabetical order, or an empty array if there is none.

Function

findPaths(maze: integer-2d-array) → string-array
mazeinteger-2d-array
the n × n grid, with 1 for an open cell and 0 for a wall
Returnsstring-array
every path from the top left to the bottom right as a string of moves, in alphabetical order

Constraints

  • 2 ≤ n ≤ 5
  • maze[i][j] is 0 or 1.
  • Every test maze has at most 2,000 paths. An open 5 × 5 maze has 8,512, so it is not in the tests.

Examples

Input
maze = [[1, 1, 0, 0], [0, 1, 1, 0], [1, 1, 1, 0], [1, 0, 1, 1]]
Output
["RDDRDR", "RDRDDR"]
Explanation
From the start only the cell to the right is open, and from there only the cell below, so both paths begin RD. RDDRDR sorts first because its third move, D, comes before R.
challenge icon

Follow-up

With all four moves allowed, can you count the paths without listing them? How large can n get before the count is out of reach?

Reset code
def findPaths(maze):
    # Write code here

Test #1

Test #2

Argument

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

Expected Output

["RDDRDR", "RDRDDR"]