-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs_dfs_un.cpp
92 lines (77 loc) · 1.75 KB
/
bfs_dfs_un.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
//Copyright@Souhardya
//Question : BFS&&DFS(Unweighed)
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define mk make_pair
#define f first
#define se second
#define ll long long int
#define ld long double
#define MOD 1000000007
void bfs(ll n,vector<vector<ll>> &v,ll src,vector<ll>&ans)
{
queue<ll>q;
q.push(src);
//vector<ll>ans;
vector<ll>vis(n,0);
while(q.size())
{
src=q.front();
vis[src]=1;
ans.pb(src);
q.pop();
for(ll i=0;i<v[src].size();i++)
{
ll tar=v[src][i];
if(vis[tar]==0)
{
vis[tar]=1;
q.push(tar);
}
}
}
}
void dfs(ll n,vector<vector<ll>> &v,ll src,vector<ll>&ans,ll *vis)
{
vis[src]=1;
ans.pb(src);
for(ll i=0;i<v[src].size();i++)
{
ll tar=v[src][i];
if(vis[tar]==0)
{
vis[tar]=1;
dfs(n,v,tar,ans,vis);
}
}
}
int main()
{
ll n,e;
cin>>n>>e;
ll src;
cin>>src;
vector<vector<ll>>v(n);
for(ll i=0;i<e;i++)
{
ll x,y;
cin>>x>>y;
v[x].pb(y);
v[y].pb(x);
}
vector<ll>ans;
cout<<"For BFS:"<<endl;
bfs(n,v,src,ans);
for(ll i=0;i<ans.size();i++)
cout<<ans[i]<<" ";
cout<<endl;
ans.clear();
ll vis[n]={0};
dfs(n,v,src,ans,vis);
cout<<"For DFS:"<<endl;
for(ll i=0;i<ans.size();i++)
cout<<ans[i]<<" ";
cout<<endl;
return 0;
}