Skip to content

Commit ef4b021

Browse files
[Leetcode] Add all paths from source to target
1 parent 27ccc76 commit ef4b021

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#include <iostream>
2+
#include <vector>
3+
4+
using namespace std;
5+
6+
using Node = int;
7+
8+
class Solution {
9+
public:
10+
vector<vector<int>> allPathsSourceTarget(vector<vector<int>> &graph);
11+
12+
private:
13+
void Dfs(Node u, const vector<vector<int>> &graph, vector<int> &path);
14+
void InitializeDegrees(const vector<vector<int>> &graph);
15+
16+
vector<vector<Node>> all_paths_;
17+
vector<int> in_degree_;
18+
vector<int> out_degree_;
19+
};
20+
21+
vector<vector<int>> Solution::allPathsSourceTarget(vector<vector<int>> &graph) {
22+
InitializeDegrees(graph);
23+
24+
vector<Node> path;
25+
Dfs(0, graph, path);
26+
27+
return all_paths_;
28+
}
29+
30+
void Solution::Dfs(Node u, const vector<vector<int>> &graph,
31+
vector<int> &path) {
32+
if (u == static_cast<Node>(graph.size()) - 1) {
33+
path.emplace_back(u);
34+
all_paths_.emplace_back(path);
35+
path.pop_back();
36+
return;
37+
}
38+
39+
path.emplace_back(u);
40+
41+
for (const Node v : graph[u]) {
42+
Dfs(v, graph, path);
43+
}
44+
45+
path.pop_back();
46+
}
47+
48+
void Solution::InitializeDegrees(const vector<vector<int>> &graph) {
49+
in_degree_.resize(graph.size());
50+
out_degree_.resize(graph.size());
51+
for (auto u = 0; u < static_cast<Node>(graph.size()); ++u) {
52+
for (const Node v : graph[u]) {
53+
++in_degree_[v];
54+
++out_degree_[u];
55+
}
56+
}
57+
}
58+
59+
int main(int argc, char *argv[]) {
60+
vector<vector<Node>> graph{{4, 3, 1}, {3, 2, 4}, {3}, {4}, {}};
61+
62+
for (const auto &path : Solution().allPathsSourceTarget(graph)) {
63+
for (const auto node : path) {
64+
cout << node << ", ";
65+
}
66+
cout << endl;
67+
}
68+
69+
return 0;
70+
}

leetcode/CMakeLists.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ set(CMAKE_CXX_STANDARD 20)
6767
add_executable(Sum_of_mutated_array_close_to_target "Practice/Medium/1300/Sum of mutated array close to target.cpp")
6868
add_executable(Deepest_leaves_sum "Practice/Medium/1302/Deepest leaves sum.cpp")
6969
add_executable(Number_of_operations_to_make_network_connected "Practice/Medium/1319/Number of operations to make network connected.cpp")
70+
add_executable(All_paths_from_source_to_target "Practice/Medium/797/All paths from source to target.cpp")
7071

7172
# Hard
7273
add_executable(Merge_k_sorted_lists "Practice/Hard/23/Merge k sorted lists.cpp")

0 commit comments

Comments
 (0)