Parcel-delivery app~20 min2s · 256 MBtarget O(rows x cols) time, O(rows x cols) spacegrid-bfs · shortest-paths
A warehouse floor plan is a grid of cells. A cell marked . is open floor, and a cell marked + is a wall. A robot stands on an open cell, called its entrance.
A dock door is an open cell on the border of the grid, other than the robot's own cell. The robot moves one step at a time, up, down, left or right, through open cells. Dispatch wants to know the fewest steps to a door and how many doors are that near.
Write nearest_exits(plan, row, col).
plan is a list of equal-length rows of . and +. The robot starts at plan[row][col], which is open.[steps, doors]: the fewest steps from the robot to any door, and the number of doors at exactly that many steps.[-1, 0] when no door can be reached.Input: plan = ["++.++", "+...+", ".....", "+...+", "++.++"], row = 2, col = 2
Output: [2, 4]The robot stands in the centre. Doors are the open border cells in the middle of each side. Each is two steps away, so four doors tie.
The solution searches ring by ring. Ring k holds the open cells exactly k steps from the robot.
| Ring | Cells in the ring | Doors in the ring |
|---|---|---|
| 1 | 4 | 0 |
| 2 | 8 | 4 |
The first ring with a door is ring 2, and it holds 4 doors, so the answer is [2, 4].
Input: plan = ["+++", "+.+", "+++"], row = 1, col = 1
Output: [-1, 0]The robot is walled in, so no door can be reached.
Input: plan = ["...."], row = 0, col = 1
Output: [1, 2]In a single row, every cell is on the border. The cells on both sides of the robot are doors, each 1 step away.
1 ≤ plan.length ≤ 200 and 1 ≤ plan[i].length ≤ 200, and every row has the same length. or +, and the robot's cell is .0 ≤ row < plan.length and 0 ≤ col < plan[row].lengthA grid of 200 × 200 has 40,000 cells. A long winding corridor can be 20,000 steps long. Repeating a sweep over all cells once for each step of distance costs about 20,000 × 40,000 = 8 × 10^8 steps. A ring search handles each cell once, about 160,000 steps in all.