Maps app~25 min2s · 256 MBtarget O(R × C) time, O(C) spaceclassic twin: lc-64dp
A walking app plans a route across a city of square blocks. Each block has an effort score, such as its hills and crossings. The walker starts at the top left block and ends at the bottom right block, and every move goes one block right or one block down.
The effort of a route is the sum of the scores of every block on it, the first and the last included. Your team lead asks: "What is the least effort of any route?"
Write least_effort(grid).
grid[r][c] is the effort score of the block in row r, column c. Every row has the same length.Input: grid = [[1, 3, 1, 2], [1, 5, 1, 4], [4, 2, 1, 3]]
Output: 10Let effort[r][c] be the least total effort to reach block (r, c). A route arrives from above or from the left, so take the cheaper of the two, then pay for the block itself: effort[r][c] = grid[r][c] + min(effort[r - 1][c], effort[r][c - 1]).
The first row can only be reached from the left, and the first column only from above.
| Row | Column 0 | Column 1 | Column 2 | Column 3 |
|---|---|---|---|---|
| 0 | 1 (start) | 4 (left 1 + 3) | 5 (left 4 + 1) | 7 (left 5 + 2) |
| 1 | 2 (above 1 + 1) | 7 (min(above 4, left 2) + 5) | 6 (min(above 5, left 7) + 1) | 10 (min(above 7, left 6) + 4) |
| 2 | 6 (above 2 + 4) | 8 (min(above 7, left 6) + 2) | 7 (min(above 6, left 8) + 1) | 10 (min(above 10, left 7) + 3) |
The last block holds 10, so the least effort is 10.
Input: grid = [[7]]
Output: 7One block: the walker starts and finishes there, so the effort is its score.
Input: grid = [[1, 2, 3], [4, 5, 6]]
Output: 12Walking along the top row and then down costs 1 + 2 + 3 + 6 = 12, the cheapest route.
1 ≤ rows ≤ 500 and 1 ≤ cols ≤ 500, and every row has the same length.0 ≤ grid[r][c] ≤ 1,000A grid of 500 by 500 blocks has 250,000 blocks and more routes than anyone could list. A table with one entry for each block takes about 250,000 small steps.