All problems

Problem 439

Rat in a Maze Paths

Medium · 20 pts · Matrix, Backtracking

Problem

A rat starts at the top-left cell (0, 0) of an N x N maze and wants to reach the bottom-right cell (N-1, N-1). Cells marked 1 are open and cells marked 0 are blocked. The rat moves one step at a time Down (D), Left (L), Right (R) or Up (U), and may not visit any cell twice on the same path. Print every possible path as a string of these letters, in lexicographic order, one per line. Print NONE if there is no path (including when the start or the end is blocked).

Input

First line: N. Next N lines: N values, each 0 or 1.

Output

Print every path in lexicographic order, one per line, or NONE.

Constraints

2 <= N <= 5

Example input

4
1 0 0 0
1 1 0 1
1 1 0 0
0 1 1 1

Example output

DDRDRR
DRDDRR

Explanation

In the maze 1 0 0 0 / 1 1 0 1 / 1 1 0 0 / 0 1 1 1, the rat can go down-down-right-down-right-right (DDRDRR) or down-right-down-down-right-right (DRDDRR). In lexicographic order DDRDRR comes first.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Euler Path or Circuit Next: Kth Ancestor Queries