Is There a Way Through
There are n towns, numbered from 0 to n − 1, and roads between them given as two lists of the same length, first and second: a road joins town first[i] and town second[i], and can be driven both ways.
Return true if you can drive from town start to town end along the roads, through as many towns as needed, and false if not. A town can always be reached from itself.
Examples
n = 4, first = [0, 1, 2], second = [1, 2, 3], start = 0, end = 3 → true
n = 5, first = [0, 3], second = [1, 4], start = 0, end = 4 → false
n = 3, first = [], second = [], start = 2, end = 2 → true
n = 6, first = [5, 0, 4, 1], second = [4, 1, 1, 2], start = 5, end = 2 → trueIn the last example the way goes 5 → 4 → 1 → 2. In the second, 0 and 1 are joined to each other, 3 and 4 to each other, and no road links the two pairs.
Constraints
- Between 1 and 10,000 towns and up to 20,000 roads; every town number is between
0andn − 1. The same road may be listed twice, and a road may lead from a town to itself. - Aim for O(n + m), n towns and m roads.
Console
›Run to see what your code prints
Run checks the 4 visible cases here, in your browser. Submit runs all 8 on the judge, 4 of them hidden, and measures how your solution scales.
Expected is the reference solution's answer, from the judge. An input that breaks the statement's other rules may get any answer.