Skip to content

Commit cfc1aa4

Browse files
authored
Merge pull request #21 from hg398/master
Added BFS in Graphs [C++] Referring issue#15
2 parents 4f9dd65 + 788797b commit cfc1aa4

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Graphs/BFS.cpp

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
//written by hg398
2+
3+
#include <bits/stdc++.h>
4+
using namespace std;
5+
vector <int> adj[100000]; //vector to implement graph using adjacency lists (size can vary a/c to need)
6+
bool mark[100000]; //array to keep record of visited nodes
7+
void bfs(int s)
8+
{
9+
queue <int> q; // Create a queue for BFS
10+
mark[s] = true; // Mark the current node as visited and enqueue it
11+
q.push(s);
12+
13+
while(!q.empty())
14+
{
15+
s = q.front(); // Dequeue a vertex from queue and print it
16+
cout << s+1 << " ";
17+
q.pop();
18+
19+
// Get all adjacent vertices of the dequeued vertex s
20+
// If a adjacent has not been visited, then mark it visited
21+
// and enqueue it
22+
for(int i = 0; i < adj[s].size(); ++i)
23+
{
24+
if(!mark[adj[s][i]])
25+
{
26+
mark[adj[s][i]] = true;
27+
q.push(adj[s][i]);
28+
}
29+
}
30+
}
31+
}
32+
33+
int main() {
34+
int nodes,edges; //no. of nodes and edges in graph
35+
cin>>nodes>>edges;
36+
while(edges--)
37+
{
38+
int a,b; //vertices between which an edge exist
39+
cin>>a>>b;
40+
a--;b--; //0-based indexing
41+
adj[a].push_back(b); //adding b to adjacency list of a to which it is directly connected
42+
adj[b].push_back(a); //adding a to adjacency list of b to which it is directly connected
43+
}
44+
memset(mark,false,sizeof(mark)); //marking all vertices unvisited
45+
int source; //source node
46+
cin>>source;
47+
bfs(source);
48+
return 0;
49+
}

0 commit comments

Comments
 (0)