LC: 1059. All Paths from Source Lead to Destination
https://leetcode.com/problems/all-paths-from-source-lead-to-destination/
1059. All Paths from Source Lead to Destination
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
sourcenode to thedestinationnodeIf 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.
Example 1:
Input: n = 3, edges = [[0,1],[0,2]], source = 0, destination = 2
Output: false
Explanation: It is possible to reach and get stuck on both node 1 and node 2.Example 2:
Input: n = 4, edges = [[0,1],[0,3],[1,2],[2,1]], source = 0, destination = 3
Output: false
Explanation: We have two possibilities: to end at node 3, or to loop over node 1 and node 2 indefinitely.Example 3:
Input: n = 4, edges = [[0,1],[0,2],[1,3],[2,3]], source = 0, destination = 3
Output: trueExample 4:
Input: n = 3, edges = [[0,1],[1,1],[1,2]], source = 0, destination = 2
Output: false
Explanation: All paths from the source node end at the destination node, but there are an infinite number of paths, such as 0-1-2, 0-1-1-2, 0-1-1-1-2, 0-1-1-1-1-2, and so on.Example 5:
Constraints:
1 <= n <= 1040 <= edges.length <= 104edges.length == 20 <= ai, bi <= n - 10 <= source <= n - 10 <= destination <= n - 1The given graph may have self-loops and parallel edges.
All Paths from Source Lead to Destination
The Essence:
Wenn eine der unteren Bedingungen durch eine Traversierung aus dem Quellknoten gelten, dann ist die Rückgabe falsch:
- Wenn ein Knoten außer dem Zielknoten keine ausgehende Kanten hat. - Wenn es Zyklen gibt. - Wenn der Zielknoten ausgehende Kanten hat.
Die Komponente aus den Kanten, die mit dem Quellknoten nicht verbunden sind, sind für Problemlösung irrelevant, da sie nicht traversiert werden.
Details:
Der beschriebene Algorithmus ist ganz einfach mit einem 2D-Array als Graph und Tiefensuche als Traversierung zu implementieren, was die Zykluserkennung einfach macht.
Solutions: The code implementation can be found here:
Default Code:
Last updated