无向图中连通分量的数目
题目链接: https://leetcode-cn.com/problems/number-of-connected-components-in-an-undirected-graph/
class Solution {
public:
vector<int> parent;
int countComponents(int n, vector<vector<int>>& edges) {
for(int i = 0; i < n; i++)
parent.push_back(i);
int cnt = n;
for(int i = 0; i < edges.size(); i++)
{
int a = edges[i][0], b = edges[i][1];
cnt -= merge(a, b);
}
return cnt;
}
int find(int x)
{
int root = x;
while(root != parent[root])
root = parent[root];
return root;
}
int merge(int a, int b)
{
int p_a = find(a);
int p_b = find(b);
if(p_a != p_b)
parent[p_a] = p_b;
return p_a != p_b;
}
};
岛屿数量
题目链接:https://leetcode-cn.com/problems/number-of-islands/
class Solution {
public:
vector<int> parent;
int numIslands(vector<vector<char>>& grid) {
if(!grid.size()) return 0;
int n = grid.size(), m = grid[0].size();
for(int i = 0; i < n * m; i++)
parent.push_back(i);
int cnt = 0;
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(grid[i][j] == '1') cnt++;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(i > 0 && grid[i][j] == '1' && grid[i - 1][j] == '1')
{
cnt -= merge(i * m + j, (i - 1) * m + j);
}
if(j > 0 && grid[i][j] == '1' && grid[i][j - 1] == '1')
{
cnt -= merge(i * m + j, i * m + j - 1);
}
}
}
return cnt;
}
int find(int x)
{
int root = x;
while(parent[root] != root)
root = parent[root];
return root;
}
int merge(int a, int b)
{
int p_a = find(a);
int p_b = find(b);
if(p_a != p_b)
parent[p_a] = p_b;
return p_a != p_b;
}
};
最长连续序列
题目链接:https://leetcode-cn.com/problems/longest-consecutive-sequence/
class Solution {
public:
unordered_map<int, int> parent, cnt;
int longestConsecutive(vector<int>& nums) {
if(!nums.size()) return 0;
for(int i : nums)
{
parent[i] = i;
cnt[i] = 1;
}
int ans = 1;
for(int num : nums)
{
if(parent.count(num + 1))
ans = max(ans, merge(num, num + 1));
}
return ans;
}
int find(int x)
{
int root = x;
while(parent[root] != root)
root = parent[root];
return root;
}
int merge(int a, int b)
{
int p_a = find(a);
int p_b = find(b);
if(p_a == p_b)
return cnt[a];
parent[p_b] = p_a;
cnt[p_a] += cnt[p_b];
return cnt[p_a];
}
};