547. 省份数量(并查集)
547. 省份数量
有 n
个城市,其中一些彼此相连,另一些没有相连。如果城市 a
与城市 b
直接相连,且城市 b
与城市 c
直接相连,那么城市 a
与城市 c
间接相连。
省份 是一组直接或间接相连的城市,组内不含其他没有相连的城市。
给你一个 n x n
的矩阵 isConnected
,其中 isConnected[i][j] = 1
表示第 i
个城市和第 j
个城市直接相连,而 isConnected[i][j] = 0
表示二者不直接相连。
返回矩阵中 省份 的数量。
示例 1:

输入:isConnected = [[1,1,0],[1,1,0],[0,0,1]] 输出:2
示例 2:

输入:isConnected = [[1,0,0],[0,1,0],[0,0,1]] 输出:3
提示:
1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j]
为1
或0
isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]
1 class Solution { 2 public: 3 vector<int> parent; // 存放当前城市所属的省份 4 int numOfProvinces; // 省份的数量 5 // vector<int> cityList; // 每个省的城市数 6 void initUnionFind(int size) { 7 parent.resize(size); 8 // cityList.resize(size); 9 for (int i = 0; i < size; i++) { 10 parent[i] = i; // 默认每个城市的省份是自己 11 // cityList[i] = 1; // 默认每个省份下都只有自己这座城市 12 } 13 numOfProvinces = size; // 默认每个城市都是一个省份 14 } 15 int findRoot(int x) { 16 int root = x; 17 while (root != parent[root]) { 18 root = parent[root]; 19 } 20 // 路径压缩 21 while (x != root) { 22 int next = parent[x]; 23 parent[x] = root; 24 x = next; 25 } 26 return root; 27 } 28 bool isConnectedbetweenTwoCities(int x, int y) { 29 return (findRoot(x) == findRoot(y)); 30 } 31 void unify(int x, int y) { 32 if (isConnectedbetweenTwoCities(x, y)) { 33 return; 34 } 35 int xRoot = findRoot(x); 36 int yRoot = findRoot(y); 37 if (xRoot < yRoot) { 38 parent[xRoot] = yRoot; 39 // cityList[yRoot] += cityList[xRoot]; 40 } else { 41 parent[yRoot] = xRoot; 42 // cityList[yRoot] += cityList[xRoot]; 43 } 44 numOfProvinces--; 45 return; 46 } 47 int findCircleNum(vector<vector<int>>& isConnected) { 48 int n = isConnected.size(); 49 initUnionFind(n); 50 // 遍历连通表合并连通的城市 51 for (int i = 0; i < n; i++) { 52 for (int j = 0; j < n; j++) { 53 if (isConnected[i][j]) { 54 unify(i, j); 55 } 56 } 57 } 58 return numOfProvinces; 59 } 60 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理