Alarm Across the Campus
Easy · Topological Sort & Shortest Paths · about 15 min
A campus has n buildings, numbered 0 to n - 1. Each [a, b, s] in links is a one-way relay: when building a hears the alarm, building b hears it s seconds later.
The alarm starts in building start at second 0. Return the number of seconds until every building has heard it, or -1 if some building never does.
1 <= n <= 1000,0 <= s <= 1000. Two buildings may have several relays between them.
Example: alarm_reach_time(4, [[0, 1, 2], [0, 2, 5], [1, 2, 1], [2, 3, 1]], 0) → 4 (building 2 hears it at second 3 through building 1, then building 3 at second 4).
Hints
- When does a building hear the alarm? At the shortest total time along relays from the start.
- Shortest times with non-negative weights: Dijkstra with a min-heap.
- Everyone has heard it when the slowest building has. Check for buildings that were never reached.
Learn the pattern first: the Topological Sort & Shortest Paths lesson.
More Topological Sort & Shortest Paths problems
- Finish Every Training Module (Easy)
- Does One Skill Lead to Another? (Easy)
- Flip the Fewest One-Way Signs (Easy)
- Letters of a Made-Up Language (Medium)
- Fewest Terms to Graduate (Medium)
- Budget Trip With Few Layovers (Medium)
- The Gentlest Hike (Medium)
- Wire Up the Sensors (Medium)
- Pick the Quietest Depot (Medium)
- Rebuild the Travel Route (Medium)
- Cross Before the Flood (Hard)
- How Many Fastest Routes? (Hard)
- Earliest Launch Day (Hard)
- Toll Roads With Coupons (Hard)