-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdfsbfs.cc
106 lines (93 loc) · 1.52 KB
/
dfsbfs.cc
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
104
105
106
#include<iostream>
#include<vector>
#include<list>
#include<stack>
#include<queue>
using namespace std;
vector<list<int> > v (50);
vector<bool> expDFS (50,false);
vector<bool> expBFS (50,false);
stack<int> s;
queue<int> q;
void addEdge(int i,int j);
void bfs();
void dfs();
void makeGraph();
void seeAdjacencyLists();
int main(){
/*
for(int i=0;i<50;i++){
list<int> l;
v.push_back(l);
}
*/
makeGraph();
s.push(1);
dfs();
q.push(1);
bfs();
return 0;
}
void dfs(){
if(!s.empty()){
int vertex = s.top();
s.pop();
if(expDFS[vertex] != true){
expDFS[vertex] = true;
cout<<vertex;
}
list<int>::iterator it;
list<int> l = v[vertex];
for(it = l.begin();it != l.end(); ++it){
if (!expDFS[*it] ){
s.push(*it);
}
}
cout<<"\n";
dfs();
}
}
void bfs(){
if(!q.empty()){
int vertex = q.front();
q.pop();
if(expBFS[vertex] != true){
expBFS[vertex] = true;
cout<<vertex;
cout<<"\n";
}
list<int>::iterator it;
list<int> l = v[vertex];
for(it = l.begin();it != l.end(); ++it){
if (!expBFS[*it]){
//cout<<"\n"<<"expBFS["<<*it<<"]not true";
q.push(*it);
}
}
bfs();
}
}
void addEdge(int i,int j){
v[i].push_back(j);
v[j].push_back(i);
}
void makeGraph(){
addEdge(1,2);
addEdge(1,5);
addEdge(1,6);
addEdge(2,6);
addEdge(5,6);
addEdge(2,3);
addEdge(3,4);
addEdge(4,5);
addEdge(2,5);
}
void seeAdjacencyLists(){
for(int i = 1;i<v.size();i++){
list<int>::iterator it;
for(it = v[i].begin();it != v[i].end();++it){
cout<<*it<<"\t";
}
cout<<"\n";
}
}