-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfsanddfs.cpp
More file actions
71 lines (66 loc) · 1.59 KB
/
bfsanddfs.cpp
File metadata and controls
71 lines (66 loc) · 1.59 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
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
class edge{
public:
int src;
int dest;
edge(int s,int d){
src=s;
dest=d;
}
};
class classroom{
public:
static void create(vector<edge>*graph,int e){
cout<<"enter source and distination:";
for(int i=0;i<e;i++){
int src,dest;
cin>>src>>dest;
graph[src].push_back(edge(src,dest));
}
}
static void bfs(vector<edge>*graph,int v){
queue<int>q;
vector<bool>visi(v,false);
q.push(0);
while(!q.empty()){
int curr=q.front();
q.pop();
if(visi[curr]==false){
cout<<curr<<" ";
visi[curr]=true;
for(int i=0;i<graph[curr].size();i++){
edge e=graph[curr][i];
q.push(e.dest);
}
}
}
}
static void dfs(vector<edge>*graph,int curr,vector<bool>& visi){
cout<<curr<<" ";
visi[curr]=true;
for(int i=0;i<graph[curr].size();i++){
edge e=graph[curr][i];
if (!visi[e.dest]) {
dfs(graph,e.dest,visi);
}
}
}
};
int main(){
int v,e,curr;
cout<<"enter a number of vertices:";
cin>>v;
cout<<"enter a number of edges:";
cin>>e;
vector<edge>*graph=new vector<edge>[v];
classroom:: create(graph,e);
cout<<"bfs traversal:";
classroom::bfs(graph,v);
cout<<"dfs traversal:";
vector<bool> visi(v, false);
classroom::dfs(graph,0,visi);
return 0;
}