Ride-hailing app~35 min2s · 256 MBtarget O(R × C × α(R × C)) time, O(R × C) spaceclassic twin: lc-827union-find
A ride-hailing app divides a city into square cells. A cell is active (1) when a driver is there, and quiet (0) otherwise. Active cells that touch at a side or at a corner belong to the same zone.
The team can send one extra driver to any quiet cell. That cell becomes active and may join several zones into one bigger zone. They want the size of the largest zone they can make, and how many quiet cells give that size.
Write best_flip(zones).
zones[r][c] is 1 for an active cell and 0 for a quiet cell.[size, ways]: the largest zone size that can result, and the number of quiet cells that give that size.[size, 0], where size is the largest zone of the grid as it is.Input: zones = [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
Output: [5, 1]The solution first labels the zones. Then for each quiet cell it adds the sizes of the different zones among its eight neighbours, plus 1 for the cell.
| Quiet cell | Active neighbours (each its own zone) | Size after switching on |
|---|---|---|
| (0, 1) | (0,0), (0,2) | 3 |
| (1, 0) | (0,0), (2,0) | 3 |
| (1, 1) | (0,0), (0,2), (2,0), (2,2) | 5 |
| (1, 2) | (0,2), (2,2) | 3 |
| (2, 1) | (2,0), (2,2) | 3 |
The centre cell touches all four corners, so it gives 5. The other four quiet cells give 3 each. The answer is [5, 1].
Input: zones = [[1, 1], [1, 1]]
Output: [4, 0]No quiet cell exists, so the largest zone is the whole grid, 4 cells.
Input: zones = [[0, 0]]
Output: [1, 2]Either quiet cell gives a zone of 1 cell, and no more, so the answer is [1, 2].
1 ≤ rows ≤ 300 and 1 ≤ columns ≤ 3000 or 1There can be up to 90,000 quiet cells. Switching each on and measuring the whole grid again would take about 8,100,000,000 steps. Labelling the zones once, and giving each quiet cell a lookup among its 8 neighbours, takes about 810,000 steps.