File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
number-of-connected-components-in-an-undirected-graph Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments