Given a directed acyclic graph (DAG) of n
nodes labeled from 0
to n - 1
, find all possible paths from node 0
to node n - 1
, and return them in any order.
The graph is given as follows: graph[i]
is a list of all nodes j
for which the edge (i, j)
exists.
0
to node n-1
.0
to n-1
.n
up to 15 or 20, giving a feasible solution space for DFS.We need to find all paths from 0
to n-1
. This can be efficiently done using Depth-First Search (DFS):
0
.n-1
, save the current path.This approach follows naturally due to the recursive nature of DFS. Given the DAG’s properties, the edges direct us without worrying about cycles.
n
.def allPathsSourceTarget(graph):
def dfs(node, path):
if node == len(graph) - 1:
result.append(path)
return
for next_node in graph[node]:
dfs(next_node, path + [next_node])
result = []
dfs(0, [0])
return result
# Example Usage
graph = [[1,2],[3],[3],[]]
print(allPathsSourceTarget(graph))
# Output: [[0, 1, 3], [0, 2, 3]]
dfs(node, path)
is a helper function that performs the DFS, starting from a given node
and forming paths.result
list to store all paths from source to target.len(graph) - 1
), append the current path to results.dfs
recursively after appending the next node to the current path.0
with the initial path containing 0
.By following this strategy, we cover all paths by exploring them recursively in a depth-first manner.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?