Created
March 25, 2017 21:37
-
-
Save FiV0/2049c2fd50bc7b8fcb6f347dd0b747dd to your computer and use it in GitHub Desktop.
Calculates a bfs-order of a graph
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <queue> | |
using namespace std; | |
/* | |
* This program reads a simple undireced graph from stdin and preforms | |
* a BFS on the given graph. The format is as follows: | |
* n m | |
* e1 e2 | |
* ... | |
* | |
* The first line contains the number of vertices and edges of | |
* the graph. The following m lines contain one edge each. | |
* An edge is represented by two distinct integers between 0 and n-1, | |
* being the two respective endpoints of the edge. | |
* | |
* */ | |
void bfs(vector<vector<int> > & g, vector<int> & order){ | |
int n = (int)g.size(); | |
vector<bool> seen(n,false); | |
queue<int> q; | |
seen[0] = true; | |
q.push(0); | |
while(!q.empty()){ | |
int x = q.front(); | |
order.push_back(x); | |
q.pop(); | |
for(auto y : g[x]){ | |
if(!seen[y]){ | |
q.push(y); | |
seen[y] = true; | |
} | |
} | |
} | |
} | |
int main(){ | |
//setting up the graph | |
int n,m; | |
cin >> n >> m; | |
vector<vector<int> > g(n,vector<int> ()); | |
vector<int> order; | |
while(m--){ | |
int a,b; | |
cin >> a >> b; | |
g[a].push_back(b); | |
g[b].push_back(a); | |
} | |
//bfs call | |
bfs(g,order); | |
//printing the order | |
cout << "One BFS order of the graph is:" << endl; | |
for(auto x: order){ | |
cout << x << " "; | |
} | |
cout << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment