Online store~30 min2s · 256 MBtarget O(rows x cols) time, O(rows x cols) spaceclassic twin: lc-2290shortest-paths · grid-bfs
A shop floor is a grid of cells. Each cell is empty, shown as 0, or holds a display stand, shown as 1. A staff member walks from the top-left cell to the bottom-right cell, one step at a time up, down, left or right.
Stands can be moved out of the way, and moving one stand costs a minute of work. The two corner cells are empty. You want the fewest stands to move so that a walk exists.
Write fewest_stands_moved(floor).
floor is a rectangle of rows, each a list of 0 and 1. A 1 is a display stand.floor[0][0] and ends at the last cell of the last row. Each step moves to a neighbouring cell.Input: floor = [[0,1,1],[1,1,0],[1,1,0]]
Output: 2The walk 0,0 to 0,1 to 0,2 to 1,2 to 2,2 passes two stands, at 0,1 and 0,2. No walk passes fewer.
The solution works level by level. Level 0 holds the cells reached with no stand moved. A stand costs one more, so it waits for the next level. The table shows the fewest stands moved to reach each cell.
| Row | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| 0 | 0 | 1 | 2 |
| 1 | 1 | 2 | 2 |
| 2 | 2 | 3 | 2 |
The bottom-right cell has cost 2, so the answer is 2. A walk with the fewest steps also has 4 steps here, and it passes two stands.
Input: floor = [[0,0],[0,0]]
Output: 0The floor is empty, so no stand has to move.
Input: floor = [[0,1,0]]
Output: 1There is only one row, so the walk crosses the stand in the middle. That stand must move.
1 ≤ floor.length ≤ 400 and 1 ≤ floor[i].length ≤ 400, and every row has the same lengthfloor[0][0] = floor[last][last] = 0A floor has up to 400 × 400 = 160,000 cells. Finding the cheapest cell with a scan of all cells, 160,000 times, costs about 2.6 × 10^10 steps. Handling each cell a constant number of times costs about 160,000 × 4 steps.