All Paths From Source Lead to Destination
1 approach, code in every language
Problem description
You are given a directed graph with n nodes labeled from 0 to n - 1, described by a list of directed edges. You are also given two nodes, source and destination.
Starting at source, consider every path that follows the edges of the graph. Determine whether all of these paths are finite and every one of them terminates exactly at destination.
Return true only when the following hold: at least one path leaves source, no reachable path can continue forever (there are no reachable cycles), and every path that can no longer be extended ends at destination. The graph may contain self-loops and parallel edges.
Example 1
Input: n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2
Output: false
The path 0 -> 1 ends at node 1, which has no outgoing edges and is not the destination, so not every path leads to destination.
Example 2
Input: n = 4, edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3
Output: true
Both branches 0 -> 1 -> 3 and 0 -> 2 -> 3 terminate at node 3, and there are no cycles, so every path reaches destination.
Constraints
1 <= n <= 10^40 <= edges.length <= 10^4edges[i].length == 20 <= from_i, to_i, source, destination <= n - 1The given graph may have self-loops and parallel edges.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free