class Solution {
public:
int Find(vector<int>& parent, int index) {
if (parent[index] != index) {
parent[index] = Find(parent, parent[index]);
}
return parent[index];
}
void Union(vector<int>& parent, int index1, int index2) {
parent[Find(parent, index1)] = Find(parent, index2);
}
int findCircleNum(vector<vector<int>>& isConnected) {
int cities = isConnected.size();
vector<int> parent(cities);
for (int i = 0; i < cities; i++) {
parent[i] = i;
}
for (int i = 0; i < cities; i++) {
for (int j = i + 1; j < cities; j++) {
if (isConnected[i][j] == 1) {
Union(parent, i, j);
}
}
}
int provinces = 0;
for (int i = 0; i < cities; i++) {
if (parent[i] == i) {
provinces++;
}
}
return provinces;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8c59e50215b6a5add78e16e693d0d9ce.jpeg)
class UnionFind {
public:
vector<int> parent;
vector<int> size;
int n;
int setCount;
public:
UnionFind(int _n): n(_n), setCount(_n), parent(_n), size(_n, 1) {
iota(parent.begin(), parent.end(), 0);
}
int findset(int x) {
return parent[x] == x ? x : parent[x] = findset(parent[x]);
}
void unite(int x, int y) {
if (size[x] < size[y]) {
swap(x, y);
}
parent[y] = x;
size[x] += size[y];
--setCount;
}
bool findAndUnite(int x, int y) {
int parentX = findset(x);
int parentY = findset(y);
if (parentX != parentY) {
unite(parentX, parentY);
return true;
}
return false;
}
};
class Solution {
public:
bool containsCycle(vector<vector<char>>& grid) {
int m = grid.size();
int n = grid[0].size();
UnionFind uf(m * n);
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i > 0 && grid[i][j] == grid[i - 1][j]) {
if (!uf.findAndUnite(i * n + j, (i - 1) * n + j)) {
return true;
}
}
if (j > 0 && grid[i][j] == grid[i][j - 1]) {
if (!uf.findAndUnite(i * n + j, i * n + j - 1)) {
return true;
}
}
}
}
return false;
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/baf70a78525601f1e5d11039a4b4a250.jpeg)
class Solution {
public:
int Find(vector<int>& parent, int index) {
if (parent[index] != index) {
parent[index] = Find(parent, parent[index]);
}
return parent[index];
}
void Union(vector<int>& parent, int index1, int index2) {
parent[Find(parent, index1)] = Find(parent, index2);
}
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n = edges.size();
vector<int> parent(n + 1);
for (int i = 1; i <= n; ++i) {
parent[i] = i;
}
for (auto& edge: edges) {
int node1 = edge[0], node2 = edge[1];
if (Find(parent, node1) != Find(parent, node2)) {
Union(parent, node1, node2);
} else {
return edge;
}
}
return vector<int>{};
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/82b7b2e89aa128ded43bf670c1efd5ba.jpeg)