Ride-hailing app~20 min2s · 256 MBtarget O(R × C) time, O(R × C) spaceclassic twin: lc-1091grid-bfs
A ride-hailing app guides riders on foot to their pickup point inside large venues, such as a stadium car park. The venue is mapped as a grid of squares. A 0 is a walkable square and a 1 is blocked: a barrier, a ramp or a closed lane.
The rider stands in the top-left square, and the pickup point is the bottom-right square. The rider can step one square up, right, down or left, and every step takes the same time. The app shows the fewest steps, or says that the pickup point cannot be reached. A venue map holds up to 400 by 400 squares.
Write fewest_moves(zone).
zone is a list of rows of 0 (walkable) and 1 (blocked). Every row has the same length.zone[0][0], and the pickup point is the bottom-right square.Input: zone = [[0, 0, 0], [1, 1, 0], [0, 0, 0]]
Output: 4BFS from (0, 0). Each square gets its move count when it joins the queue.
| Taken from the queue | Moves | Joins the back | Queue after |
|---|---|---|---|
| (0, 0) | 0 | (0, 1) at 1 | (0, 1) |
| (0, 1) | 1 | (0, 2) at 2 | (0, 2) |
| (0, 2) | 2 | (1, 2) at 3 | (1, 2) |
| (1, 2) | 3 | (2, 2) at 4 | (2, 2) |
| (2, 2) | 4 | the pickup point: stop |
The blocked squares in the middle row force the walk round the right side.
Input: zone = [[0, 1], [1, 0]]
Output: -1Both squares next to the rider are blocked, so the queue runs dry before the pickup point.
Input: zone = [[0]]
Output: 0The rider is already standing on the pickup point.
1 ≤ rows, columns ≤ 400, and every row has the same lengthThe size here is the number of squares: up to 400 × 400 = 160,000. BFS handles each square once with four neighbour checks, which is under a million steps.
Trying every walk from the start, or relaxing distances by sweeping the grid until nothing improves, repeats work. A winding walkway needs tens of thousands of sweeps of 160,000 squares, which is far too slow.