-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.cpp
51 lines (39 loc) · 1.32 KB
/
solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// DFS
class Solution {
void dfs(vector<vector<int>>& graph, int source, int destination, vector<int> list, vector<vector<int>>& result) {
list.push_back(source);
if(source == destination) result.push_back(list);
for(int vertex: graph[source]) {
vector<int> currentList(list);
dfs(graph, vertex, destination, currentList, result);
}
}
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> result;
dfs(graph, 0, graph.size() - 1, {}, result);
return result;
}
};
// BFS
class Solution {
public:
vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
vector<vector<int>> result;
int destination = graph.size() - 1;
queue<vector<int>> q;
q.push({0});
while(!q.empty()) {
vector<int> path = q.front();
q.pop();
int current = path[path.size() - 1];
if(current == destination) result.push_back(path);
for(int node: graph[current]) {
vector<int> newPath(path);
newPath.push_back(node);
q.push(newPath);
}
}
return result;
}
};