There are n cities, some of which are connected to each other, and some are not connected. If city a and city b are directly connected, and city b is directly connected to city c, then city a and city c are indirectly connected.
A province is a group of directly or indirectly connected cities. The group does not contain other unconnected cities.
Give you an nxn matrix isConnected, where isConnected[i][j] = 1 means that the ith city and the jth city are directly connected, and isConnected[i][j] = 0 means that the two are not directly connected.
Returns the number of provinces in the matrix.
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
prompt:
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]
Source: LeetCode
Link: https://leetcode-cn.com/problems/number-of-provinces
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Idea: This question is simpler than yesterday's. It should have happened yesterday. If you use dfs to write this question, it is very simple. I will post an official one and check the collection to learn (learning template hhhh)
class Solution {
public int findCircleNum(int[][] isConnected) {
int provinces = isConnected.length;
int[] parent = new int[provinces];
for (int i = 0; i < provinces; i++) {
parent[i] = i;
}
for (int i = 0; i < provinces; i++) {
for (int j = i + 1; j < provinces; j++) {
if (isConnected[i][j] == 1) {
union(parent, i, j);
}
}
}
int circles = 0;
for (int i = 0; i < provinces; i++) {
if (parent[i] == i) {
circles++;
}
}
return circles;
}
public void union(int[] parent, int index1, int index2) {
parent[find(parent, index1)] = find(parent, index2);
}
public int find(int[] parent, int index) {
if (parent[index] != index) {
parent[index] = find(parent, parent[index]);
}
return parent[index];
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/number-of-provinces/solution/sheng-fen-shu-liang-by-leetcode-solution-eyk0/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。