547. Number of Provinces
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3Last updated
Input: isConnected = [[1,1,0],[1,1,0],[0,0,1]]
Output: 2Input: isConnected = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3Last updated
public int findCircleNum(int[][] matrix) {
int count = 0, n = matrix.length;
boolean[] visited = new boolean[n]; //标记是否已经检查过这个i
for (int i = 0; i < matrix.length; i++) {
// 如果我们已经检查过i,说明这个i和别的地方是连着的,不需要继续
if (visited[i]) continue;
// 发现一个新的城市/省,把它周围的所有邻居都标记上
count++;
dfs(matrix, visited, i);
}
return count;
}
private void dfs(int[][] matrix, boolean[] visited, int i) {
visited[i] = true; // 标记这个i已经被访问过了
for (int j = 0; j < matrix.length; j++) {
if (i == j || visited[j] || matrix[i][j] == 0) continue;
dfs(matrix, visited, j);
}
}public int findCircleNum(int[][] matrix) {
int count = 0, n = matrix.length;
boolean[] visited = new boolean[n];
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (visited[i]) continue;
q.offer(i);
while (!q.isEmpty()) {
int j = q.poll();
visited[j] = true;
for (int k = 0; k < n; k++) {
if (matrix[j][k] == 1 && !visited[k]) q.offer(k);
}
}
count++;
}
return count;
}class Solution {
// Union Find
public int findCircleNum(int[][] isConnected) {
if (isConnected == null || isConnected.length == 0) {
return 0;
}
int n = isConnected.length;
UnionFind uf = new UnionFind(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (isConnected[i][j] == 1) {
uf.union(i, j);
}
}
}
return uf.getCount();
}
class UnionFind {
private int[] root;
private int[] rank;
private int count;
UnionFind(int size) {
root = new int[size];
rank = new int[size];
count = size;
for (int i = 0; i < size; i++) {
root[i] = i;
rank[i] = 1;
}
}
int find(int x) {
if (x == root[x]) {
return x;
}
return root[x] = find(root[x]);
}
void union(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX != rootY) {
if (rank[rootX] > rank[rootY]) {
root[rootY] = rootX;
} else if (rank[rootX] < rank[rootY]) {
root[rootX] = rootY;
} else {
root[rootY] = rootX;
rank[rootX] += 1;
}
count--;
}
}
int getCount() {
return count;
}
}
}public int findCircleNum(int[][] matrix) {
int count = 0, n = matrix.length;
// 这是union find的setup
int[] root = new int[n];
for (int i = 0; i < n; i++) root[i] = i;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (matrix[i][j] == 1) union(root, i, j);
}
}
for (int i = 0; i < n; i++) {
if (root[i] == i) count++;
}
return count;
}
private void union(int[] root, int x, int y) {
root[find(root, x)] = find(root, y);
}
private int find(int[] root, int x) {
if (x == root[x]) return x;
return root[x] = find(root, root[x]);
}