Skip to content

Commit 2adfbc0

Browse files
committed
Number of Connected Components solution
1 parent 9498bba commit 2adfbc0

File tree

1 file changed

+37
-0
lines changed
  • number-of-connected-components-in-an-undirected-graph

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
public:
3+
/**
4+
* @param n: the number of vertices
5+
* @param edges: the edges of undirected graph
6+
* @return: the number of connected components
7+
*/
8+
void dfs(int curr, vector<vector<int>>& graph, vector<bool>& visited){
9+
visited[curr] = true;
10+
11+
for(int i = 0; i < graph[curr].size(); i++){
12+
if(visited[graph[curr][i]] == false)
13+
dfs(graph[curr][i], graph, visited);
14+
}
15+
}
16+
17+
int countComponents(int n, vector<vector<int>> &edges) {
18+
// write your code here
19+
vector<bool> visited(n, 0);
20+
vector<vector<int>> graph (n);
21+
int cnt = 0;
22+
23+
for(int i = 0; i < edges.size(); i++){
24+
graph[edges[i][0]].push_back(edges[i][1]);
25+
graph[edges[i][1]].push_back(edges[i][0]);
26+
}
27+
28+
for(int i = 0; i < n; i++){
29+
if(visited[i] == false){
30+
dfs(i, graph, visited);
31+
cnt++;
32+
}
33+
}
34+
35+
return cnt;
36+
}
37+
};

0 commit comments

Comments
 (0)