713. Paths Around Rocks

Medium3.5 points estimatedArrayDynamic ProgrammingMatrix3 hints

A hiker crosses a flooded valley described by grid, where grid[r][c] is the water depth of a cell. A cell is passable when its depth is at most 6; deeper cells are flooded and cannot be entered. The start (top-left) and the finish (bottom-right) are always treated as passable, whatever their depth.

From a cell the hiker may only step one cell right or one cell down. Return the number of different routes from the start to the finish, modulo 1000000007. If no route exists, return 0.

Aim for time O(rows * cols) and extra space O(cols).

Example 1

Input:
grid = [[0,2,1,1],[3,8,0,0],[1,0,0,4]]
Output:
4
Explanation:

Only the cell of depth 8 is flooded; it blocks 6 of the 10 monotone routes, leaving 4.

Example 2

Input:
grid = [[1,1,1,1,1],[2,2,2,2,2]]
Output:
5
Explanation:

With no flooded cells the hiker only chooses the column where the single step down is taken, giving 5 routes.

Constraints

1 ≤ rows, cols ≤ 300

0 ≤ grid[r][c] ≤ 100

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(rows * cols)
Space
O(cols)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…