Maps app~15 min2s · 256 MBtarget O(n + m) time, O(n + m) spacecycle-detection
You work on a maps app. A district has n junctions, numbered 0 to n - 1, and two-way footpaths between some pairs of them.
A street-cleaning planner asks one question. Do any footpaths form a closed loop, so a cleaner can walk out and come back without using a footpath twice? Footpaths that run between the same two junctions count as separate footpaths. The district may be several separate parts, and any part can hold the loop.
Write has_loop(n, roads).
n is the number of junctions.roads[i] = [a, b] is a two-way footpath between junctions a and b, with a ≠ b.true when the footpaths contain a closed loop, and false otherwise.Input: n = 6, roads = [[0, 1], [1, 2], [2, 3], [3, 1], [3, 4], [0, 5]]
Output: trueJunctions 1, 2 and 3 form a loop. Walk from junction 0 with a stack, and mark each junction when you put it on the stack.
| Step | Take | Arrived by road | Stack after | Seen after |
|---|---|---|---|---|
| 1 | 0 | none | 1, 5 | 0, 1, 5 |
| 2 | 5 | 5 | 1 | 0, 1, 5 |
| 3 | 1 | 0 | 2, 3 | 0, 1, 2, 3, 5 |
| 4 | 3 | 3 | road 2 leads to junction 2, already seen: loop |
Input: n = 4, roads = [[0, 1], [1, 2], [2, 3]]
Output: falseA single path. Every road leads to a new junction, so there is no loop.
Input: n = 2, roads = [[0, 1], [0, 1]]
Output: trueTwo footpaths join the same two junctions. Walk out on one and back on the other.
1 ≤ n ≤ 100,0000 ≤ len(roads) ≤ 100,000, and every row is [a, b] with 0 ≤ a, b < n and a ≠ bThere can be 100,000 junctions and 100,000 roads. Testing every road by searching the map again is 100,000 searches of up to 200,000 steps each, about 20 billion steps. The answer must touch each junction and road a few times: n + m.