The problem, in one line. Given points joined by two-way links, say whether you can get from one named point to another by following links. LeetCode 1971.
The tell. The question is “can I get there at all?” and no link has a length or a price. That is plain reachability, and every shortest-path tool starts from it: spread outward from the start and see whether the target is touched.
The wrong first idea
Follow links depth first, and only remember the route you are on right now.
def walk(x, route):
if x == destination:
return True
return any(walk(y, route | {x}) for y in graph[x] if y not in route)
It is correct, and it is a trap. It forgets a point as soon as it backs out, so the next route walks through the same point again. On 20 points that all link to each other there are more distinct routes than anyone can count, and every one gets tried when the answer is “no”.
The invariant
Keep one set, seen, for the whole search. A point goes into it the moment it is queued, and it is never queued again.
flowchart LR A["queue: 0<br/>seen: 0"] --> B["pop 0, queue 1<br/>seen: 0, 1"] B --> C["pop 1, queue 2<br/>seen: 0, 1, 2"] C -->|"pop 2 = target"| D["True"]
The sentence that stays true every step: every point in seen is either already expanded or waiting in the queue, so no point is ever queued twice. Each point and each link is touched once, which is why the “no” answer is as cheap as the “yes”.
The solution
from collections import deque
def valid_path(n, edges, source, destination):
graph = [[] for _ in range(n)]
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
seen = {source} # a node is queued once, never twice
queue = deque([source])
while queue:
x = queue.popleft()
if x == destination:
return True
for y in graph[x]:
if y not in seen:
seen.add(y)
queue.append(y)
return False
print(valid_path(5, [[0, 1], [1, 2], [3, 4]], 0, 2))
print(valid_path(5, [[0, 1], [1, 2], [3, 4]], 0, 4))
print(valid_path(1, [], 0, 0))
True
False
True
func validPath(n int, edges [][]int, source, destination int) bool {
graph := make([][]int, n)
for _, e := range edges {
graph[e[0]] = append(graph[e[0]], e[1])
graph[e[1]] = append(graph[e[1]], e[0])
}
seen := map[int]bool{source: true} // a node is queued once, never twice
queue := []int{source}
for len(queue) > 0 {
x := queue[0]
queue = queue[1:]
if x == destination {
return true
}
for _, y := range graph[x] {
if !seen[y] {
seen[y] = true
queue = append(queue, y)
}
}
}
return false
}
Same three calls print true, false, true.
Complexity
- Time O(n + e): each point is queued once and each link is looked at from both ends.
- Space O(n + e): the adjacency lists hold every link twice, and
seenholds every point.
Traps
- Adding each link in one direction only. With the single link
[[0, 1]], asking for a path from 1 to 0 then answers False. - Marking a point as seen when it is popped instead of when it is queued. The same point sits in the queue many times, and a graph where every point links to every other blows up.
- Skipping the check when the start is the target. With one point and no links the answer is True, and the loop above gets it only because it tests the target after popping.
Next in the ladder
Network Delay Time walks the same graph, but every link now has a travel time, so the plain queue becomes a heap that always serves the nearest point first.