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, that is:
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.
graph LR;
A(0):::blue --> B(1) & D(3):::green
B --- C(2)
C ---B
classDef green fill:#3CB371,stroke:#000,stroke-width:1px,color:#fff;
classDef blue fill:#0000FF,stroke:#000,stroke-width:1px,color:#fff;
1
2
3
Input: n =4, edges =[[0,1],[0,3],[1,2],[2,1]], source =0, destination =3Output: falseExplanation: We have two possibilities: to end at node 3, or to loop over node 1 and node 2 indefinitely.
graph LR;
A(0):::blue --> B(1) & C(2)
B --> D(3):::green
C --- D
classDef green fill:#3CB371,stroke:#000,stroke-width:1px,color:#fff;
classDef blue fill:#0000FF,stroke:#000,stroke-width:1px,color:#fff;
1
2
Input: n =4, edges =[[0,1],[0,2],[1,3],[2,3]], source =0, destination =3Output: true
We need to ensure that every path from source leads to destination and nowhere else, and that there are no cycles (which would allow infinite paths). If we ever reach a node with no outgoing edges that isn’t destination, or revisit a node in the current path (cycle), we return false.
classSolution {
publicbooleanleadsToDestination(int n, int[][] edges, int src, int dest) {
List<Integer>[] g =new List[n];
for (int i = 0; i < n; ++i) g[i]=new ArrayList<>();
for (int[] e : edges) g[e[0]].add(e[1]);
int[] vis =newint[n];
return dfs(g, vis, src, dest);
}
booleandfs(List<Integer>[] g, int[] vis, int u, int dest) {
if (g[u].isEmpty()) return u == dest;
if (vis[u]== 1) returnfalse;
if (vis[u]== 2) returntrue;
vis[u]= 1;
for (int v : g[u]) {
if (!dfs(g, vis, v, dest)) returnfalse;
}
vis[u]= 2;
returntrue;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funleadsToDestination(n: Int, edges: Array<IntArray>, src: Int, dest: Int): Boolean {
val g = Array(n) { mutableListOf<Int>() }
for (e in edges) g[e[0]].add(e[1])
val vis = IntArray(n)
fundfs(u: Int): Boolean {
if (g[u].isEmpty()) return u == dest
if (vis[u] ==1) returnfalseif (vis[u] ==2) returntrue vis[u] = 1for (v in g[u]) if (!dfs(v)) returnfalse vis[u] = 2returntrue }
return dfs(src)
}
}