Ride-hailing app~25 min2s · 256 MBtarget O(r c) time, O(r c) spaceclassic twin: lc-695dfs
A ride-hailing app divides a city into square cells. A cell holds 1 when demand is high there and 0 otherwise. Two high-demand cells belong to the same zone when they share a side. Cells that touch only at a corner are not in the same zone.
The operations team sends extra drivers to the biggest zone. They want its area: the number of cells in it. A grid can have up to 300 rows and 300 columns.
Write largest_zone(cells).
cells[r][c] is 1 for a high-demand cell and 0 for any other cell.Input: cells = [[1,1,0,0,0], [1,0,0,1,1], [0,0,0,1,1], [0,1,0,0,1]]
Output: 5The solution scans the grid in reading order. Each time it meets a high-demand cell that is not yet visited, it starts a flood fill and counts the cells it reaches.
| Start cell (row, column) | Cells reached | Area | Largest so far |
|---|---|---|---|
| (0, 0) | (0,0), (0,1), (1,0) | 3 | 3 |
| (1, 3) | (1,3), (1,4), (2,3), (2,4), (3,4) | 5 | 5 |
| (3, 1) | (3,1) | 1 | 5 |
The largest zone has 5 cells.
Input: cells = [[0, 0], [0, 0]]
Output: 0No cell has high demand.
Input: cells = [[1, 0], [0, 1]]
Output: 1The two cells touch only at a corner, so each is a zone of one cell.
1 ≤ cells.length ≤ 300 and 1 ≤ cells[r].length ≤ 300 (a rectangle)A grid has up to 90,000 cells. Starting a fresh flood fill from every high-demand cell would repeat the work of a zone once for each of its cells. For one zone of 90,000 cells that is about 8 × 10^9 steps. Each cell should be visited once in total.