Ctrl K

Long Leaps Across a Board

Hard
You get a board board with m rows and n columns filled with non-negative integers. You stand in the top-left cell (0, 0) and want to reach the bottom-right cell (m - 1, n - 1). From the cell (i, j) holding v = board[i][j] a single move can take you: - right along the same row to any cell (i, k) with j < k ≤ j + v; - down the same column to any cell (k, j) with i < k ≤ i + v. Return the smallest number of cells you have to visit on the way, counting both the start and the finish. If the finish cannot be reached, return -1.
Example 1
board=[[1, 3, 2], [0, 0, 0], [0, 0, 0]] → 4

The route (0, 0) → (0, 1) → (0, 2) → (2, 2): the value 2 at (0, 2) lets you drop two rows at once. That is 4 cells, counting both the start and the finish.

Example 2
board=[[4, 0, 0, 0, 0]] → 2

From the start you can leap straight to the last cell, so 2 cells are visited.

Example 3
board=[[2, 0, 0], [0, 0, 0], [0, 0, 0]] → -1

Only cells holding 0 are reachable from the start, and there is nowhere to go from them.

Constraints
  • 1 ≤ m, n
  • m · n ≤ 10⁵
  • 0 ≤ board[i][j] < m · n
  • board[m - 1][n - 1] = 0
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBiggest Solid Panel Block HardCrossing at High Tide HardHow Far the Water Spreads HardRoute With the Highest Bottleneck MediumAll-Ones Rectangles Medium
loading Python…
Input
board=[[1, 3, 2], [0, 0, 0], [0, 0, 0]]
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.