Skip to content

Commit 74f2e9d

Browse files
committed
#797. All Paths From Source to Target
1 parent bf3329a commit 74f2e9d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1,
2+
# find all possible paths from node 0 to node n - 1 and return them in any order.
3+
4+
# The graph is given as follows: graph[i] is a list of all nodes you can visit from
5+
# node i (i.e., there is a directed edge from node i to node graph[i][j]).
6+
7+
8+
# Example 1:
9+
# Input: graph = [[1,2],[3],[3],[]]
10+
# Output: [[0,1,3],[0,2,3]]
11+
# Explanation: There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
12+
13+
# Example 2:
14+
# Input: graph = [[4,3,1],[3,2,4],[3],[4],[]]
15+
# Output: [[0,4],[0,3,4],[0,1,3,4],[0,1,2,3,4],[0,1,4]]
16+
17+
18+
# Constraints:
19+
20+
# n == graph.length
21+
# 2 <= n <= 15
22+
# 0 <= graph[i][j] < n
23+
# graph[i][j] != i (i.e., there will be no self-loops).
24+
# All the elements of graph[i] are unique.
25+
# The input graph is guaranteed to be a DAG.
26+
27+
28+
from typing import List
29+
class Solution:
30+
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
31+
ans = []
32+
def dfs(s, path):
33+
if len(graph) - 1 == s:
34+
ans.append(path)
35+
return
36+
for i in graph[s]:
37+
dfs(i, path+[i])
38+
dfs(0, [0])
39+
return ans

0 commit comments

Comments
 (0)