-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraphCB.cpp
More file actions
105 lines (96 loc) · 2.16 KB
/
graphCB.cpp
File metadata and controls
105 lines (96 loc) · 2.16 KB
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
#include<bits/stdc++.h>
using namespace std;
class Graph{
int V; //vertices
list<int> *adjList; //Array of LL of size v
public:
Graph(int v){
V = v;
adjList = new list<int>[V];
}
void addEdge(int u, int v, bool bidir = true){
adjList[u].push_back(v);
if(bidir){
adjList[v].push_back(u);
}
}
void printGraph(){
for(int i = 0; i < V; i++){
cout << i << "->";
for(int node : adjList[i]){
cout << node << ", ";
}
cout << endl;
}
}
};
//Graph implementation with hashmaps
//template for generic graph
template<typename T>
class Graph_{
map<T, list<T> >adjList;
public:
Graph_(){
}
void addEdge(T u, T v, bool bidir = true){
adjList[u].push_back(v);
if(bidir){
adjList[v].push_back(u);
}
}
void printGraph(){
for(auto everyrow : adjList){
cout << everyrow.first << " -> ";
for(T x : everyrow.second){
cout << x << " , ";
}
cout << endl;
}
}
};
void dfs(int s, vector<int> g[], bool vis[]){
vis[s] = true;
cout << s << " ";
for(int i = 0; i < g[s].size(); i++){
if(vis[g[s][i]] == false){
dfs(g[s][i], g, vis);
}
}
}
int number_connectedComponents(vector<int> g[], int n, bool vis[]){
int cc_count = 0;
for(int i = 0; i <= n; i++){
if(vis[i] == 0){
dfs(i, g, vis);
cc_count++;
}
}
return cc_count;
}
int main(){
// Graph g(4);
// g.addEdge(0,1);
// g.addEdge(0,2);
// g.addEdge(0,3);
// g.addEdge(1,3);
// g.addEdge(3,2);
// g.printGraph();
// Graph_<string> g;
// g.addEdge("A", "D");
// g.addEdge("A", "J");
// g.addEdge("D", "S");
// g.printGraph();
int N, E;
cin >> N;
vector<int> g[N]; //graph adj List
bool vis[N];
memset(vis, false, sizeof(vis));
for(int i = 0; i < N; i++){
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
dfs(1, g, vis);
return 0;
}