DFS through the DAG
Since the size of the input node is 2 <= n <= 15, the approach does not need to be super efficient
Start from the first node and traverse through the directed edges by calling dfs iteratively
Have the path saved as the parameter to the dfs function
When the traversal reaches the end node (n), append the path to the result and end traversing
class Solution:
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
def dfs(path):
if path[-1] == len(graph) - 1:
res.append(path)
return
for v in graph[path[-1]]:
dfs(path + [v])
res = []
dfs([0])
return res
n: number of edges
Time Complexity: O(n) - O(n^2) depending on the shape of the DAG
Approach
https://leetcode.com/problems/all-paths-from-source-to-target/description/
DFS through the DAG Since the size of the input node is
2 <= n <= 15
, the approach does not need to be super efficientn: number of edges
O(n)
-O(n^2)
depending on the shape of the DAGO(n)
as result arrayhttps://leetcode.com/problems/all-paths-from-source-to-target/solutions/986429/python-iterative-dfs-with-detailed-time-complexity-visuals/?orderBy=most_votes