-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs_dfs.cpp
More file actions
90 lines (72 loc) · 1.77 KB
/
bfs_dfs.cpp
File metadata and controls
90 lines (72 loc) · 1.77 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <Node.hpp>
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
void DFS(Node *start)
{
stack<Node *> s;
s.push(start);
while (!s.empty()) {
auto current_node = s.top();
s.pop();
if (current_node->visited)
continue;
current_node->visited = true;
cout << "=========================================" << endl;
cout << "Current Node: " << current_node->val << endl;
for (auto neighbor : current_node->neighbors) {
cout << "Neighbors: " << neighbor->val << ", ";
if (!neighbor->visited) {
s.push(neighbor);
}
}
cout << endl
<< "=========================================" << endl;
}
}
void BFS(Node *start)
{
queue<Node *> q;
q.push(start);
while (!q.empty()) {
auto current_node = q.front();
q.pop();
if (current_node->visited)
continue;
current_node->visited = true;
cout << "=========================================" << endl;
cout << "Current Node: " << current_node->val << endl;
for (auto neighbor : current_node->neighbors) {
cout << "Neighbors: " << neighbor->val << ", ";
if (!neighbor->visited) {
q.push(neighbor);
}
}
cout << endl
<< "=========================================" << endl;
}
}
int main(int argc, char *argv[])
{
Node *n1 = new Node(1);
Node *n2 = new Node(2);
Node *n3 = new Node(3);
Node *n4 = new Node(4);
Node *n5 = new Node(5);
Node *n6 = new Node(6);
Node *n7 = new Node(7);
vector<Node *> allNodes = {n1, n2, n3, n4, n5, n6, n7};
n1->neighbors = {n2, n5, n7};
n2->neighbors = {n1, n3};
n3->neighbors = {n4, n5};
n4->neighbors = {n3, n6};
n5->neighbors = {n1, n3, n6};
n6->neighbors = {n4, n5, n7};
n7->neighbors = {n1, n6};
BFS(n1);
for (auto n : allNodes) {
cout << "Val: " << n->val << ", " << n->visited << endl;
}
return 0;
}