-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBFS_DFS.cpp
More file actions
75 lines (73 loc) · 1.74 KB
/
Copy pathBFS_DFS.cpp
File metadata and controls
75 lines (73 loc) · 1.74 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
72
73
74
75
#include<bits/stdc++.h>
using namespace std;
class Graph
{
int V;
list<int>*adj;
public:
Graph(int V)
{
this->V = V;
this->adj = new list<int>[V];
}
void addedge(int u,int v)
{
this->adj[u].push_back(v);
}
void BFS(int source)
{
vector<bool>visited(this->V,false);
list<int>q;
q.push_back(source);
visited[source] = true;
while(!q.empty())
{
source = q.front();
q.pop_front();
cout<<source<<" ";
for(auto itr=this->adj[source].begin();itr!=this->adj[source].end(); itr++)
{
if(visited[*itr]==false)
{
visited[*itr] =true;
q.push_back(*itr);
}
}
}
}
void DFSHelper(vector<bool>& visited,int source)
{
visited[source] = true;
cout<<source<<" ";
for(auto itr = this->adj[source].begin();itr!=this->adj[source].end();itr++)
{
if(!visited[*itr])
{
DFSHelper(visited,*itr);
}
}
}
void DFS()
{
vector<bool>visited(this->V,false);
for(int v=0;v<this->V;v++)
{
if(!visited[v])
{
DFSHelper(visited,v);
}
}
}
};
int main()
{
Graph g(4);
g.addedge(0,1);
g.addedge(0,2);
g.addedge(1,2);
g.addedge(2,0);
g.addedge(2,3);
g.addedge(3,3);
g.BFS(0);
g.DFS();
}