Loading
Loading
A rural county has n junctions numbered 0 to n − 1, joined by two-way roads. Each entry of roads is a pair [a, b] meaning a road runs between junctions a and b.
A courier is at junction start and must deliver to junction finish. Return true if some sequence of roads connects them.
n = 6, roads = [[0,1],[1,2],[3,4],[4,5]], start = 0, finish = 5{0} {1} {2} {3} {4} {5}every junction starts alone{0,1,2} {3} {4} {5}roads 0–1 and 1–2 merge three junctions{0,1,2} {3,4,5}roads 3–4 and 4–5 merge the rest0 and 5 apartdifferent groups, so no routefalseSign in to keep a note here. It is free, and nobody else can see it.
Sign inExample 1
| 0 | 0 | 1 |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 3 | 4 |
| 3 | 4 | 5 |
Sign in to open hints.
Struggling is where the learning happens. Open this once you have genuinely tried, or once the hints have run out.
O(n + roads) time · O(n) space
Input. Run your code to watch it work on this input, one line at a time.
| 0 | 0 | 1 |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 3 | 4 |
| 3 | 4 | 5 |
Running code is turned off on this deployment. You can still read the problem, write code, use hints and the visualizer.
Tab moves focus out of the editor. Press Ctrl+M to let Tab indent instead.
No results yet
Run your code against the sample tests, or submit to run the full suite.
0 → 1 → 2.
Example 2
| 0 | 0 | 1 |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 3 | 4 |
| 3 | 4 | 5 |
Nodes 0, 1, 2 and nodes 3, 4, 5 form two separate networks.
Example 3
Start and finish are the same junction.