Created
August 12, 2018 06:13
-
-
Save sr6033/3d4a018fc0ae598616ca11f134e060c5 to your computer and use it in GitHub Desktop.
Depth 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; | |
| vector<bool> v; | |
| // Undirected graph | |
| void addEdge(int a, int b) | |
| { | |
| g[a].push_back(b); | |
| g[b].push_back(a); | |
| } | |
| void dfsVisit(int u) | |
| { | |
| v[u] = true; | |
| cout << u << " "; | |
| for(auto i = g[u].begin(); i != g[u].end(); i++) | |
| { | |
| if(!v[*i]) | |
| dfsVisit(*i); | |
| } | |
| } | |
| void dfs(int n) | |
| { | |
| for(int u = 0; u < n; u++) | |
| { | |
| if(!v[u]) | |
| dfsVisit(u); | |
| } | |
| } | |
| 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); | |
| } | |
| dfs(n); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment