-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathdfs.cpp
142 lines (110 loc) · 2.64 KB
/
dfs.cpp
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
//tree n nodes h to n-1 edges hogi
//tree are non cyclic graph
//lca lowest comman ancestor are first comman parent of two nodes
//in order to store tree we use adjacant matrix or adjacant list
//In Adjacant matrix space complexity is more O(N^2) but it is easy to check node is connected or not
//In Adjacant list space complexity is less O(V+E) but for connection check we iterate all via loop
//full bt have either 0 or child
//complete bt have all level filled except last or have left as possible
//perfect bt have all leaf node at same level
//balance bt have height log(no of nodes)
// degenerate bt have single children of all nodes
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
vector<int> g[N];
bool vis[N];
void dfs(int vertex){
cout<<vertex<<endl;
vis[vertex] = true;
for(int child : g[vertex]){
cout<<"par "<<vertex<<", child "<<child<<endl;
if(vis[child]) continue;
dfs(child);
}
}
int main(){
int n,m;
int v1,v2;
cin>>n>>m;
for(int i=0;i<m;++i){
cin>>v1>>v2;
g[v1].push_back(v2);
g[v2].push_back(v1);
}
dfs(1);
}
/*
//Count no of connected components
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
vector<int> g[N];
bool vis[N];
void dfs(int vertex){
vis[vertex] = true;
for(int child : g[vertex]){
if(vis[child]) continue;
dfs(child);
}
}
int main(){
int n,m;
int v1,v2;
int cnt=0;
cin>>n>>m;
for(int i=0;i<m;++i){
cin>>v1>>v2;
g[v1].push_back(v2);
g[v2].push_back(v1);
}
for(int i=1;i<=n;i++){
if(vis[i]) continue;
dfs(i);
cnt++;
}
cout<<cnt<<endl;
}
*/
/*
// print all connected components
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
vector<int> g[N];
bool vis[N];
vector<vector<int>> cc;
vector<int> c;
void dfs(int vertex){
vis[vertex] = true;
c.push_back(vertex);
for(int child : g[vertex]){
if(vis[child]) continue;
dfs(child);
}
}
int main(){
int n,m;
int v1,v2;
int cnt=0;
cin>>n>>m;
for(int i=0;i<m;++i){
cin>>v1>>v2;
g[v1].push_back(v2);
g[v2].push_back(v1);
}
for(int i=1;i<=n;i++){
if(vis[i]) continue;
c.clear();
dfs(i);
cc.push_back(c);
}
cout<<cc.size()<<endl;
for(auto i:cc){
for(auto j:i){
cout<<j<<" ";
}
cout<<endl;
}
}
*/