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 source node to the destination node
  • If a path exists from the source node to a node with no outgoing edges, then that node is equal to destination
  • The number of possible paths from source to destination is 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
All Paths from Source Lead to Destination INPUT Directed Graph 0 source 1 2 3 destination edges = [[0,1],[0,2], [1,3],[2,3]] source = 0 destination = 3 ALGORITHM STEPS DFS with Three States 1 Build Adjacency List 0: [1,2], 1: [3], 2: [3] 2 Define States UNVISITED, VISITING, VISITED 3 DFS from Source Detect cycles (VISITING) 4 Verify Leaf Nodes Leaf must be destination DFS Traversal 0: Visit 1: Visit 3: Leaf OK 2: Visit 3: Leaf OK All paths reach node 3 FINAL RESULT Path Analysis Complete Path 1: 0 --> 1 --> 3 Ends at destination: OK Path 2: 0 --> 2 --> 3 Ends at destination: OK Verification [OK] No cycles detected [OK] All leaves = dest [OK] Finite paths Output: true Key Insight: Use THREE states (UNVISITED, VISITING, VISITED) to detect cycles. A node in VISITING state means we're still exploring its paths - revisiting it indicates a cycle. Also verify that EVERY leaf node equals destination. TutorialsPoint - All Paths from Source Lead to Destination | DFS with Three States
Asked in
Google 15 Facebook 12 Microsoft 8
35.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen