Skip to content

Commit 3fc28cf

Browse files
Added Day-24 Solution
1 parent fa79e44 commit 3fc28cf

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'''
2+
Given a directed, acyclic graph of N nodes. 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: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.
5+
6+
Example:
7+
Input: [[1,2], [3], [3], []]
8+
Output: [[0,1,3],[0,2,3]]
9+
Explanation: The graph looks like this:
10+
0--->1
11+
| |
12+
v v
13+
2--->3
14+
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
15+
Note:
16+
17+
The number of nodes in the graph will be in the range [2, 15].
18+
You can print different paths in any order, but you should keep the order of nodes inside one path.
19+
20+
21+
22+
'''
23+
24+
class Solution:
25+
def allPathsSourceTarget(self, graph: List[List[int]]) -> List[List[int]]:
26+
N = len(graph)
27+
paths = [[] for _ in range(N)]
28+
# Base Case
29+
paths[-1].append([N-1])
30+
31+
def dfs(node):
32+
# Check if we already have paths available for the current node
33+
if not paths[node]:
34+
for nbr in graph[node]:
35+
res = dfs(nbr)
36+
# Add current node to each path from neighbour node to target node
37+
for r in res:
38+
paths[node].append([node] + r)
39+
40+
return paths[node]
41+
42+
dfs(0)
43+
return paths[0]

0 commit comments

Comments
 (0)