Given n
nodes labeled from 0
to n - 1
and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
Example 1:
0 3 | | 1 --- 2 4
Given n = 5
and edges = [[0, 1], [1, 2], [3, 4]]
, return 2
.
Example 2:
0 4 | | 1 --- 2 --- 3
Given n = 5
and edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
, return 1
.
Note:
You can assume that no duplicate edges will appear in edges
. Since all edges are undirected, [0, 1]
is the same as [1, 0]
and thus will not appear together in edges
.
思路:并查集(Union find)
1 class Solution { 2 public: 3 int getFather(vector<int>& father, int i) { 4 if (father[i] == i) return i; 5 father[i] = getFather(father, father[i]); 6 return father[i]; 7 } 8 void merge(vector<int>& father, int i, int j) { 9 int fatherI = getFather(father, i); 10 int fatherJ = getFather(father, j); 11 father[fatherJ] = fatherI; 12 } 13 int countComponents(int n, vector<pair<int, int>>& edges) { 14 vector<int> father; 15 for (int i = 0; i < n; i++) father.push_back(i); 16 for (int i = 0, n = edges.size(); i < n; i++) 17 merge(father, get<0>(edges[i]), get<1>(edges[i])); 18 unordered_set<int> unions; 19 for (int i = 0; i < n; i++) unions.insert(getFather(father, i)); 20 return unions.size(); 21 } 22 };
时间: 2024-11-03 21:36:54