当前位置:网站首页>[leetcode] 547. Number of provinces (medium)
[leetcode] 547. Number of provinces (medium)
2022-07-28 00:33:00 【Bright morning light】
One 、 subject
1、 Title Description
Yes n Cities , Some of them are connected to each other , Others are not connected . If the city a And the city b Direct connection , And the city b And the city c Direct connection , So the city a And the city c Indirectly connected .
Province It's a group of directly or indirectly connected cities , There are no other cities in the group that are not connected .
To give you one n x n Matrix isConnected , among isConnected[i][j] = 1 It means the first one i Two cities and j The two cities are directly connected , and isConnected[i][j] = 0 The two are not directly connected .
Back in the matrix Province The number of .
Example 1:
Input :isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output :2
Example 2:
Input :isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output :3
2、 Basic framework
3、 Original link
Two 、 Problem solving report
1、 Thought analysis
Use the union search set to put the connected islands into the same set , Finally, you only need to determine the number of sets
2、 Time complexity
3、 Code details
C++ edition
Writing a : It makes full use of rank merging and path compression of the union search set
class Solution {
public:
class UnionFind {
public:
vector<int> parents; // Record the father of each element
vector<int> size; // Record the number of elements representing the set of elements
vector<int> help; // Auxiliary array , Used for path compression
int sets; // The number of sets
UnionFind(int n) {
parents.resize(n);
size.resize(n);
help.resize(n);
sets = n;
for (int i = 0; i < n; i++) {
parents[i] = i;
size[i] = 1;
}
}
int find(int i) {
int hi = 0;
while (i != parents[i]) {
help[hi++] = i;
i = parents[i];
}
for (hi--; hi >= 0; hi--) {
// Path compression
parents[help[hi]] = i;
}
return i;
}
void myUnion(int i, int j) {
int fi = find(i), fj = find(j);
if (fi != fj) {
// Rank consolidation , Hang the representative node with fewer elements in the set to the representative node with more elements in the set
if (size[fi] >= size[fj]) {
parents[fj] = fi;
size[fi] += size[fj];
} else {
parents[fi] = fj;
size[fj] += size[fi];
}
sets--;
}
}
int setSize() {
return sets;
}
};
int findCircleNum(vector<vector<int>>& isConnected) {
UnionFind *uf = new UnionFind(isConnected.size());
for (int i = 0; i < isConnected.size(); i++) {
for (int j = i + 1; j < isConnected.size(); j++) {
if (isConnected[i][j] == 1) {
uf->myUnion(i, j);
}
}
}
return uf->setSize();
}
};
Write two : Only the path compression of joint search set is used , Rank merging is not used
class Solution {
public:
int find(vector<int> &parents, int i) {
return parents[i] == i ? i : parents[i] = find(parents, parents[i]);
}
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
int ans = n;
vector<int> parents(n);
for (int i = 0; i < n; i++) {
parents[i] = i; // initialization , Each element is in a separate set
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (isConnected[i][j] == 1) {
int fi = find(parents, i), fj = find(parents, j);
if (fi != fj) {
// Not merged by rank
parents[fi] = fj;
ans--;
}
}
}
}
return ans;
}
};
Java edition
// The title is leetcode The original title is
// Test link :https://leetcode.com/problems/friend-circles/
public class FriendCircles {
public static int findCircleNum(int[][] M) {
int N = M.length;
// {0} {1} {2} {N-1}
UnionFind unionFind = new UnionFind(N);
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
if (M[i][j] == 1) {
// i and j Know each other
unionFind.union(i, j);
}
}
}
return unionFind.sets();
}
public static class UnionFind {
// parent[i] = k : i His father is k
private int[] parent;
// size[i] = k : If i Represents the node ,size[i] It makes sense , Otherwise, it doesn't make sense
// i What is the size of the collection
private int[] size;
// Auxiliary structure
private int[] help;
// How many collections are there
private int sets;
public UnionFind(int N) {
parent = new int[N];
size = new int[N];
help = new int[N];
sets = N;
for (int i = 0; i < N; i++) {
parent[i] = i;
size[i] = 1;
}
}
// from i Start all the way up , Up to no more up , Represents a node , return
// This process requires path compression
private int find(int i) {
int hi = 0;
while (i != parent[i]) {
help[hi++] = i;
i = parent[i];
}
for (hi--; hi >= 0; hi--) {
parent[help[hi]] = i;
}
return i;
}
public void union(int i, int j) {
int f1 = find(i);
int f2 = find(j);
if (f1 != f2) {
if (size[f1] >= size[f2]) {
size[f1] += size[f2];
parent[f2] = f1;
} else {
size[f2] += size[f1];
parent[f1] = f2;
}
sets--;
}
}
public int sets() {
return sets;
}
}
}
边栏推荐
- 这种动态规划你见过吗——状态机动态规划之股票问题(中)
- 英特尔携手汉朔、微软,释放“AI + 零售”大招!
- Have you ever seen this kind of dynamic programming -- the stock problem of state machine dynamic programming (Part 2)
- code review 工具
- Intel joins hands with hanshuo and Microsoft to release the "Ai + retail" trick!
- JS ATM output
- MFC提示this application has requested the runtime to terminate it in an unusual way editbox框已经删了还在使用
- 几行代码轻松实现对于PaddleOCR的实时推理,快来get!
- Is there a general formula for tens of millions of players? B station is underestimated as a hot money opportunity!
- 窗口函数over
猜你喜欢

BuildForge 资料

MATLAB | 那些你不得不知道的MATLAB小技巧(二)

7月第3周榜单丨飞瓜数据B站UP主排行榜发布!

What are the namespaces and function overloads of + and @ in front of MATLAB folder
![[C language] string reverse order (recursive implementation)](/img/a1/9e603321d364c7f457116bd9e462aa.png)
[C language] string reverse order (recursive implementation)

What a beautiful rainbow

英特尔发布开源AI参考套件

MATLAB 文件夹前面的+和@是干啥的 命名空间与函数的重载

英特尔AI实践日第56期 | 探讨行业发展新趋势

What foundation does Yolo need? How to learn Yolo?
随机推荐
Application scenario Display of metauniverse
Understand the parental delegation model
窗口函数over
抖音直播监控-循环值守24小时-直播弹幕
2022 latest Tiktok live broadcast monitoring full set of monitoring (V) product details monitoring
threejs个人笔记
require、loadfile、dofile、load、loadstring
"Digital economy, science and technology for the good" talk about dry goods
永州清洁级动物实验室建设选址注意事项
每次读取一行字符串输入(有待补充)
Diffusion + super-resolution model strong combination, the technology behind Google image generator image
Smart convenience store takes you to unlock the future technology shopping experience
渲染问题
英特尔发布开源AI参考套件
图片提取文字很神奇?试试三步实现OCR!
Glory launched a number of products at the same time. The price of notebook magicbook V 14 starts from 6199 yuan
MFC prompts that this application has requested the runtime to terminate it in an unused way editbox box has been deleted and is still in use
阿金的思考
MATLAB 文件夹前面的+和@是干啥的 命名空间与函数的重载
几行代码轻松实现对于PaddleOCR的实时推理,快来get!