Last active
August 11, 2018 17:57
-
-
Save sr6033/96264d03564baf854e9652a685a36c25 to your computer and use it in GitHub Desktop.
Breadth First Search using C++ STL
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 <bits/stdc++.h> | |
| using namespace std; | |
| vector <vector <int>> g; // Graph vector | |
| vector <bool> v; // Visited nodes | |
| // Directed Graph | |
| void addEdge(int a, int b) | |
| { | |
| g[a].push_back(b); | |
| } | |
| void bfs(int u) | |
| { | |
| queue<int> q; | |
| q.push(u); | |
| v[u] = true; // visited | |
| while(!q.empty()) | |
| { | |
| int node = q.front(); | |
| q.pop(); | |
| cout << node << " "; | |
| for(auto i = g[node].begin(); i != g[node].end(); i++) | |
| { | |
| if(!v[*i]) | |
| { | |
| q.push(*i); | |
| v[*i] = true; | |
| } | |
| } | |
| } | |
| } | |
| int main() | |
| { | |
| int n, e; | |
| cin >> n >> e; | |
| v.assign(n, false); | |
| g.assign(n, vector<int>()); | |
| int a, b; | |
| for(int i = 0; i < e; i++) | |
| { | |
| cin >> a >> b; | |
| addEdge(a,b); | |
| } | |
| // Checking for disconnected nodes | |
| for(int i = 0; i < n; i++) | |
| { | |
| if(!v[i]) | |
| bfs(i); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment