Maps app~12 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-1971dfs
A metro map app lets riders ask whether two stations are connected at all, for example before a line closes for work. The network has n stations, numbered 0 to n - 1, joined by two-way tracks. You work on the app's route checker.
Your team lead says: "Riders do not need the best route here. They need a yes or no: can I get from this station to that one, changing trains as often as I like?"
Write has_route(n, tracks, start, goal).
n is the number of stations.tracks[i] = [a, b] is a two-way track between stations a and b.start and goal are two stations.true when some chain of tracks leads from start to goal, and false otherwise. A station is always connected to itself, so start == goal returns true.Input: n = 7, tracks = [[0, 1], [0, 2], [1, 3], [4, 5], [5, 6]], start = 0, goal = 3
Output: trueThe search keeps a stack of stations it has found but not yet visited. Neighbours are pushed in the order the tracks list them.
| Taken from the stack | Pushed | Stack after (top on the right) |
|---|---|---|
| 0 | 1, 2 | 1, 2 |
| 2 | none | 1 |
| 1 | 3 | 3 |
| 3 | goal reached | empty |
Station 3 came off the stack, so the chain 0, 1, 3 exists.
Input: n = 7, tracks = [[0, 1], [0, 2], [1, 3], [4, 5], [5, 6]], start = 0, goal = 6
Output: falseStations 4, 5 and 6 form a separate network. No track joins it to stations 0 to 3.
Input: n = 1, tracks = [], start = 0, goal = 0
Output: trueOne station is connected to itself.
1 ≤ n ≤ 100,0000 ≤ len(tracks) ≤ 200,000, and every track is [a, b] with 0 ≤ a, b < n and a ≠ b. A pair may appear more than once.0 ≤ start, goal < nThere can be 100,000 stations and 200,000 tracks. A search that visits each station once and looks at each track twice takes about 500,000 steps. Passing over all the tracks again and again, once for every station, would take about 20 billion steps.