All Paths from Source Lead to Destination - Problem
Given the edges of a directed graph where edges[i] = [ai, bi] indicates there is an edge between nodes ai and bi, and two nodes source and destination of this graph, determine whether or not all paths starting from source eventually end at destination.
This means:
- At least one path exists from the
sourcenode to thedestinationnode - If a path exists from the
sourcenode to a node with no outgoing edges, then that node is equal todestination - The number of possible paths from
sourcetodestinationis a finite number
Return true if and only if all roads from source lead to destination.
Input & Output
Example 1 — Valid Path Structure
$
Input:
edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3
›
Output:
true
💡 Note:
There are two paths from source 0 to destination 3: 0→1→3 and 0→2→3. Both paths end at destination 3, and there are no cycles, so return true.
Example 2 — Wrong Destination
$
Input:
edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 2
›
Output:
false
💡 Note:
Path 0→1→3 ends at node 3, not at the specified destination 2. Since not all paths lead to destination, return false.
Example 3 — Cycle Present
$
Input:
edges = [[0,1],[1,1],[1,2]], source = 0, destination = 2
›
Output:
false
💡 Note:
There is a self-loop at node 1 (1→1), creating an infinite cycle. This violates the finite paths requirement, so return false.
Constraints
- 1 ≤ edges.length ≤ 104
- edges[i].length == 2
- 0 ≤ ai, bi ≤ 103
- 0 ≤ source ≤ 103
- 0 ≤ destination ≤ 103
Visualization
Tap to expand
Understanding the Visualization
1
Input Graph
Directed graph with edges, source node, and destination node
2
Path Validation
Check all possible paths using DFS with cycle detection
3
Result
True if all paths end at destination with no infinite loops
Key Takeaway
🎯 Key Insight: Use three-state DFS (WHITE/GRAY/BLACK) to detect cycles while ensuring all leaf nodes equal the destination
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code