-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.cpp
88 lines (73 loc) · 1.47 KB
/
graph.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
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
#include "iostream"
#include "vector"
#include "stack"
#include "queue"
#define REP(i, n) for(int i = 0; i < n; i++)
using namespace std;
vector<int> adj[10];
bool visitedDFS[10];
bool visitedBFS[10];
// stack 1 2
// x 0
void dfs(int start) {
stack<int> s;
s.push(start);
visitedDFS[start] = true;
int x;
while(!s.empty()) {
x = s.top();
cout << "Visited : " << x << '\n';
s.pop();
for(int i = 0; i < adj[x].size(); i++) {
int neighbor = adj[x][i];
if (!visitedDFS[neighbor]) {
s.push(neighbor);
visitedDFS[neighbor] = true;
// cout << "Visited : " << neighbor << '\n';
}
}
}
}
void bfs(int start) {
queue<int> q;
q.push(start);
visitedBFS[start] = true;
int x;
while(!q.empty()) {
x = q.front();
cout << "Visited : " << x << '\n';
q.pop();
for(int i = 0; i < adj[x].size(); i++) {
int neighbor = adj[x][i];
if (!visitedBFS[neighbor]) {
q.push(neighbor);
visitedBFS[neighbor] = true;
// cout << "Visited : " << neighbor << '\n';
}
}
}
}
// adds edge from x to y
void addEdge(int x, int y) {
adj[x].push_back(y);
}
int main()
{
int nodes, edges;
int x, y;
cin >> nodes >> edges;
for(int i = 0; i < edges; i++) {
cin >> x >> y;
addEdge(x, y);
}
// for(int i = 0; i < nodes; i++) {
// cout << "Adjacency list of node : " << i << '\n';
// for(int j = 0; j < adj[i].size(); j++) cout << adj[i][j] << ' ';
// cout << '\n';
// }
cout << "DFS : \n";
dfs(0);
cout << "BFS : \n";
bfs(0);
return 0;
}