-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgraph_traversal.cpp
103 lines (77 loc) · 1.28 KB
/
graph_traversal.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <bits/stdc++.h>
using namespace std;
vector<int> adj[10];
int level[10];
bool visit[10];
int src;
void BFS()
{
cout << "Running BFS..." <<endl;
queue <int> q;
q.push(src);
level[src] = 0;
visit[src] = 0;
while(!q.empty())
{
int p = q.front();
q.pop();
for (int i = 0; i < adj[p].size(); ++i)
{
if(visit[ adj[p][i] ] == false)
{
level[ adj[p][i] ] = level[ p ] + 1;
q.push( adj[p][i]);
visit[ adj[p][i] ] = true;
}
}
if (!q.empty())
cout << "Top of the queue: "<< q.front() << endl;
}
}
void DFS()
{
cout << endl << "Running DFS..."<<endl;
stack <int> s;
s.push(src);
level[src] = 0;
visit[src] = 0;
while(!s.empty())
{
int p = s.top();
s.pop();
for (int i = adj[p].size()-1; i > -1; --i)
{
if(visit[ adj[p][i] ] == false)
{
level[ adj[p][i] ] = level[p] + 1;
s.push( adj[p][i] );
visit[adj[p][i]] = true;
//cout << "Current node: "<<adj[p][i] << endl;
}
}
if (!s.empty())
{
cout << "Top of the stack: "<<s.top()<<endl;
}
}
}
int main()
{
int nodes,edges;
cin >> nodes >> edges;
int x,y;
for (int i = 0; i < edges; ++i)
{
cin >> x >> y;
if(i == 0) src = x;
adj[x].push_back(y);
}
BFS();
for(int i=0;i<10;i++)
{
level[i] = 0;
visit[i] = false;
}
DFS();
return 0;
}