Problem · Matrix

Enumerate Right-and-Down Matrix Paths

Learn this problem
MediumOracle logoOracleFULLTIMEONSITE INTERVIEW

Problem statement

You are given a non-empty rectangular binary matrix grid. A cell containing 1 is valid, and a cell containing 0 is blocked.

Enumerate every valid path from the top-left cell to the bottom-right cell. Each move must go exactly one cell Down or one cell Right, and every visited cell must contain 1.

Represent a path as a string containing 'D' and 'R'. Return all path strings in lexicographic order. If either endpoint is blocked or no valid path exists, return an empty list. A valid 1-by-1 matrix has one path represented by the empty string.

Function

enumeratePaths(grid: int[][]) → List<String>

Examples

Example 1

grid = [[1,1,1],[1,1,1]]return = ["DRR","RDR","RRD"]

All three monotone paths stay on valid cells. Because 'D' precedes 'R', their lexicographic order is "DRR", "RDR", then "RRD".

Example 2

grid = [[1,0],[1,1]]return = ["DR"]

The first Right move is blocked, so the only path moves Down and then Right.

Example 3

grid = [[1]]return = [""]

The start is already the destination. The unique path contains no moves, so it is represented by the empty string.

Example 4

grid = [[1,0],[0,1]]return = []

Both possible first moves enter blocked cells, so no path reaches the destination.

Constraints

  • 1 <= grid.length <= 100 and 1 <= grid[i].length <= 100.
  • Every row has the same length.
  • Every cell is either 0 or 1.
  • The total number of valid paths is at most 10000.

More Oracle problems

drafts saved locally
public List<String> enumeratePaths(int[][] grid) {
  // write your code here
}
grid[[1,1,1],[1,1,1]]
expected["DRR","RDR","RRD"]
checking account