Maps app~20 min2s · 256 MBtarget O(n² α(n)) time, O(n) spaceclassic twin: lc-547union-find
A maps app keeps a table of driving times between towns. Entry minutes[i][j] is the direct driving time from town i to town j in minutes, or 0 when there is no direct road. The table is the same in both directions.
The app draws a region around towns that are close together. Two towns are linked when a direct road between them takes at most limit minutes. A region is a set of towns that reach one another through linked towns.
You count the regions.
Write regions_within_limit(minutes, limit).
minutes is a square table with n rows and n columns, one for each town. minutes[i][j] equals minutes[j][i], and minutes[i][i] is 0.limit minutes.Input: minutes = [[0,12,0,0,40],[12,0,9,0,0],[0,9,0,30,0],[0,0,30,0,0],[40,0,0,0,0]], limit = 15
Output: 3The solution starts with five regions of one town. It reads each pair of towns once, above the diagonal, and joins the two regions when the road exists and is short enough.
| Pair | Minutes | Linked | Regions after |
|---|---|---|---|
0, 1 |
12 | yes | 4 |
0, 4 |
40 | no | 4 |
1, 2 |
9 | yes | 3 |
2, 3 |
30 | no | 3 |
The regions are towns 0, 1 and 2, then town 3, then town 4. The answer is 3.
Input: minutes = [[0,12,0,0,40],[12,0,9,0,0],[0,9,0,30,0],[0,0,30,0,0],[40,0,0,0,0]], limit = 30
Output: 2The road between towns 2 and 3 takes exactly 30 minutes, so it counts. Towns 0 to 3 form one region and town 4 is alone.
Input: minutes = [[0,12,0,0,40],[12,0,9,0,0],[0,9,0,30,0],[0,0,30,0,0],[40,0,0,0,0]], limit = 8
Output: 5The shortest road takes 9 minutes, so no town is linked with another. Every town is a region of its own.
1 ≤ n ≤ 600, where n is the number of rows, and 1 ≤ limit ≤ 1,000,0000 ≤ minutes[i][j] ≤ 1,000,000, the table is symmetric and its diagonal is 0A table of 600 towns has 360,000 entries, and half of them repeat the other half. Reading each pair once costs about 180,000 steps. Spreading labels again and again until nothing changes can need up to 600 sweeps of 360,000 entries, which is 216,000,000 steps.