π One-stop destination for all your technical interview Preparation π
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 you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
This process can be implemented using a BFS traversal as -
3 <= k <= n
) nodes, we have k-2 intermediate nodes and we can choose from n-2 available nodes. Thus the resulting time complexity is Ξ£ n-2Ck-2
for all 3 <= k <= n
, which comes out to be O(2N-2) = O(2N)
class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph)
{
vector<vector<int>> ans;
queue<vector<int>> q;
q.push({ 0 }); // push the initial source
while (q.size()) {
auto path = move(q.front()); // efficiently copy (pointer copy)
q.pop();
if (path.back() == graph.size() - 1) // found valid path
ans.push_back(move(path));
else
for (auto x : graph[path.back()]) { // try every possible next node in path
path.push_back(x);
q.push(path); // push path into queue for further exploration
path.pop_back();
}
}
return ans;
}
};
The process of finding all paths using DFS can be implemented as -
The above process continues till every possible path is tried out by dfs.
class Solution {
private:
void dfs(int src, int dest, vector<vector<int>>& graph, vector<int>& curr, vector<vector<int>>& ans)
{
if (src == dest) { // base condition - found a path
ans.push_back(curr);
return;
}
for (int x : graph[src]) {
curr.push_back(x); // DO
dfs(x, dest, graph, curr, ans); // RECUR
curr.pop_back(); // UNDO/Backtrack
}
}
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph)
{
vector<vector<int>> ans;
vector<int> curr;
curr.push_back(0); // push the initial source
dfs(0, graph.size() - 1, graph, curr, ans); // dfs(src,dest,graph,curr,ans)
return ans;
}
};