Parcel-delivery app~30 min2s · 256 MBtarget O(paths) in the worst case, cut by the bound time, O(cells) spaceclassic twin: lc-1219backtracking
A parcel-delivery app runs a warehouse with a rectangular floor. Each cell holds some items, and a cell with 0 items is empty. A picking robot starts on any cell that holds items.
The robot moves up, down, left or right onto a cell that holds items. It never steps on the same cell twice, and it empties every cell it visits. A route must end at a door, which is any cell on the border of the floor.
Write best_route(shelves).
shelves is a list of rows of whole numbers. shelves[r][c] is the number of items on that cell, and 0 means empty.0 when no route can end at a door.Input: shelves = [[0,6,0],[5,8,7],[0,9,0]]
Output: 24The solution tries a route from every cell with items. It marks each cell on the route, and unmarks it on the way back. The table shows the best route from each start that ends at a door.
| Start cell | Best route | Items |
|---|---|---|
| (0, 1) | 6, 8, 9 | 23 |
| (1, 0) | 5, 8, 9 | 22 |
| (1, 1) | 8, 9 | 17 |
| (1, 2) | 7, 8, 9 | 24 |
| (2, 1) | 9, 8, 7 | 24 |
The best total is 24. The centre cell is the only cell that is not a door.
Input: shelves = [[4,0,0,7],[0,9,9,0],[0,9,9,0],[3,0,0,6]]
Output: 7The four middle cells hold 36 items, but they are cut off from the border by empty cells. A route inside them can never end at a door. The best route is the single corner with 7 items.
Input: shelves = [[0,0,0,0],[0,9,9,0],[0,9,9,0],[0,0,0,0]]
Output: 0No cell with items is on the border, so no route can end at a door.
1 ≤ rows, columns ≤ 50 ≤ shelves[r][c] ≤ 100A floor with 25 cells has millions of routes if every cell holds items. A search that tries each of them is slow but finishes. You can do much better by stopping a route that can not beat the best total found so far.