难度中等669收藏分享切换为中文接收动态反馈
There are
n
cities. Some of them are connected, while some are not. If citya
is connected directly with cityb
, and cityb
is connected directly with cityc
, then citya
is connected indirectly with cityc
.A province is a group of directly or indirectly connected cities and no other cities outside of the group.
You are given an
n x n
matrixisConnected
whereisConnected[i][j] = 1
if theith
city and thejth
city are directly connected, andisConnected[i][j] = 0
otherwise.Return the total number of provinces.
Example 1:
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]] Output: 2Example 2:
Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]] Output: 3Constraints:
1 <= n <= 200
n == isConnected.length
n == isConnected[i].length
isConnected[i][j]
is1
or0
.isConnected[i][i] == 1
isConnected[i][j] == isConnected[j][i]
dfs:
class Solution {
public int findCircleNum(int[][] isConnected) {
int length = isConnected.length;
boolean[] visited = new boolean[length];
int res = 0;
for(int i = 0;i < length;i++){
//节点里默认为false,说明此时还没有元素更改或者没有与其想连的省份
if(!visited(i)){
dfs(isConnected,visited,i);
res++;
}
}
return res;
}
public void dfs(int[][] arr,boolean[] visit,int i){
for(int j = 0;j < arr.length;j++){
if(arr[i][j] == 1 && !visit[j]){
visit[i][j] = true;
dfs(arr,visit,j);
}
}
}
}
并查集
public class Solution {
class UnionFind {
private int count = 0;
private int[] parent, rank;
public UnionFind(int n) {
count = n;
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public int find(int p) {
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
if (rank[rootQ] > rank[rootP]) {
parent[rootP] = rootQ;
}
else {
parent[rootQ] = rootP;
if (rank[rootP] == rank[rootQ]) {
rank[rootP]++;
}
}
count--;
}
public int count() {
return count;
}
}
public int findCircleNum(int[][] M) {
int n = M.length;
UnionFind uf = new UnionFind(n);
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (M[i][j] == 1) uf.union(i, j);
}
}
return uf.count();
}
}