-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraversal.cpp
More file actions
54 lines (46 loc) · 1.4 KB
/
Copy pathtraversal.cpp
File metadata and controls
54 lines (46 loc) · 1.4 KB
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
52
53
54
#include <vector>
#include <stack>
#include <queue>
#include <unordered_set>
#include "node.hpp"
#include "traversal.hpp"
std::vector<Node*> dfs(Node* startNode){
std::vector<Node*> visitOrder;
std::stack<Node*> openList;
openList.emplace(startNode);
std::unordered_set<Node*> visited;
visited.insert(startNode);
while (!openList.empty()){
Node* n = openList.top(); //Visit Node n
openList.pop();
visitOrder.emplace_back(n); //Store visit order
std::vector<Node*> adjacentNodes = n->getAdjacencyList();
for(Node* m : adjacentNodes){
if (visited.find(m) == visited.end()) {
openList.push(m);
visited.insert(m);
}
}
}
return visitOrder;
}
std::vector<Node*> bfs(Node* startNode){
std::vector<Node*> visitOrder;
std::queue<Node*> openList;
openList.emplace(startNode);
std::unordered_set<Node*> visited;
visited.insert(startNode);
while (!openList.empty()){
Node* n = openList.front(); //Visit Node n
openList.pop();
visitOrder.emplace_back(n); //Store visit order
std::vector<Node*> adjacentNodes = n->getAdjacencyList();
for(Node* m : adjacentNodes){
if (visited.find(m) == visited.end()) {
openList.push(m);
visited.insert(m);
}
}
}
return visitOrder;
}