Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector<int> adj[100]; //adjacency list (an array of vectors)
- bool visited[100]; //to keep track which vertices are visited
- void DFS(int v){
- //terminate function if vertex is visited
- if(visited[v]==true) return;
- visited[v]=true; //mark as visited
- cout<<v<<" "; //prints out current vertex
- //for each vertex connected to current vertex, do DFS (recursive function)
- for(int i=0;i<adj[v].size();i++){
- int x=adj[v][i];
- if(!visited[x]) DFS(x);
- }
- }
- int main()
- {
- int V,E; //specify no of vertices,V and edges,E
- cin>>V>>E;
- //create adjacency list (input E pairs of vertices that are connected by an edge)
- for(int i=0;i<E;i++){
- int a,b;
- cin>>a>>b;
- adj[a].push_back(b);
- adj[b].push_back(a);
- }
- DFS(0); //start DFS from vertex 0
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement