-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_TG-DFS.cpp
More file actions
40 lines (35 loc) · 860 Bytes
/
basic_TG-DFS.cpp
File metadata and controls
40 lines (35 loc) · 860 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//Basic of Graph - Depth first search.
//It state that trasverse to last element of vetices and go on till the
//last child. Whenever we encounter any visited element just skip it.
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+10;
vector<int> graph[N];
bool vis[N];
void dfs(int v){
//take action on vertex after entering the vertex
cout<<v<<endl;
vis[v]=true;
for(auto child:graph[v]){
// take action on child before entering child node
// cout<<"p "<<v<<" c "<<child<<endl;
if(vis[child]) continue;
cout<<"p "<<v<<" c "<<child<<endl;
dfs(child);
//take action on child before exiting child node
}
//take action on vertex before exiting the vertex
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=0; i<m; ++i){
int v1,v2;
cin>>v1>>v2;
graph[v1].push_back(v2);
graph[v2].push_back(v1);
}
dfs(1);
return 0;
}