All Paths Source to Target — DFS Backtracking
Advertisement
Problem
Find all paths from node 0 to node n-1 in a directed acyclic graph.
Solutions
Python
class Solution:
def allPathsSourceTarget(self, graph: list[list[int]]) -> list[list[int]]:
target=len(graph)-1; result=[]
def dfs(node, path):
if node==target: result.append(list(path)); return
for nb in graph[node]:
path.append(nb); dfs(nb,path); path.pop()
dfs(0,[0]); return result
C++
class Solution {
vector<vector<int>> res;
void dfs(vector<vector<int>>& g, int node, vector<int>& path){
if(node==g.size()-1){res.push_back(path);return;}
for(int nb:g[node]){path.push_back(nb);dfs(g,nb,path);path.pop_back();}
}
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& g){
vector<int> p={0}; dfs(g,0,p); return res;
}
};
Complexity
- Time: O(2^V * V) | Space: O(2^V * V) — exponential paths possible in DAG
Advertisement