Leetcode 797. All Paths From Source to Target
You are given a directed, acyclic graph (DAG) of n
nodes labeled from 0
to n - 1
, represented by a list of n
lists. Each list graph[i]
is a list of nodes i
can travel to directly.
Your task is to find all possible paths from node 0
to node n - 1
and return them in any order.
0
to node n-1
?Assuming the answers to these questions are yes for a valid DAG, yes for at least one path, and any order is acceptable, let’s proceed to design the solution.
0
to the target node n-1
.#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
void dfs(vector<vector<int>>& graph, vector<int>& path, vector<vector<int>>& result, int node) {
// Add node to the current path
path.push_back(node);
// If we reach the last node, add the path to the result
if (node == graph.size() - 1) {
result.push_back(path);
} else {
// Recursively visit all adjacent nodes
for (int nextNode : graph[node]) {
dfs(graph, path, result, nextNode);
}
}
// Backtrack
path.pop_back();
}
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> result;
vector<int> path;
dfs(graph, path, result, 0);
return result;
}
};
int main() {
Solution sol;
vector<vector<int>> graph = \{\{1, 2}, {3}, {3}, {}};
vector<vector<int>> result = sol.allPathsSourceTarget(graph);
for (const auto& path : result) {
for (int node : path) {
cout << node << " ";
}
cout << endl;
}
return 0;
}
V
be the number of vertices and E
be the number of edges in the graph.O(2^V * V)
. The 2^V
part comes from the number of possible paths and V
comes from the cost of copying the path to the result.O(V)
for the recursion stack used in DFS and the path list. Additionally, we store the result, which in the worst case can have up to 2^V
paths, each of length V
.This method should efficiently find all paths from the source to the target node in a DAG, adhering to the given problem’s requirements.
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?