Skip to content

Commit 6b76568

Browse files
committed
Depth First Algorithm in C++
1 parent b4374be commit 6b76568

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#include<bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
vector<int> adj[1000]; //adjacency list of graph
6+
bool visited[1000]={false} ; //array to keep track of visited nodes
7+
8+
void bfs(int source)
9+
{
10+
visited[source] = true;
11+
12+
queue<int> q;
13+
q.push(source);
14+
15+
while(!q.empty())
16+
{
17+
source = q.front() ;
18+
q.pop();
19+
20+
for(int i=0; i<adj[source].size() ;i++) //visiting neighbours of source vertex
21+
{
22+
int neighbour = adj[source][i];
23+
if( !visited[neighbour])
24+
{
25+
visited[neighbour] = true;
26+
q.push(neighbour);
27+
}
28+
}
29+
}
30+
31+
}
32+
33+
int main()
34+
{
35+
int vertices,edges;
36+
cin>>vertices>>edges;
37+
38+
for(int i=0; i<edges ; i++)
39+
{
40+
int u,v;
41+
cin>>u>>v;
42+
adj[u].push_back(v);
43+
adj[v].push_back(u);
44+
}
45+
46+
int source;
47+
cin>>source;
48+
49+
bfs(source);
50+
51+
return 0;
52+
}

0 commit comments

Comments
 (0)