1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| class Solution { private static class UnionFind { private final int[] parent;
public UnionFind(int n) { this.parent = new int[n]; for (int i = 0; i < parent.length; i++) { parent[i] = i; } }
public void union(int x, int y) { int xRoot = getRoot(x), yRoot = getRoot(y); if (xRoot == yRoot) { return; }
parent[xRoot] = yRoot; }
private int getRoot(int x) { if (parent[x] != x) { parent[x] = getRoot(parent[x]); } return parent[x]; }
}
public int countServers(int[][] grid) { int m = grid.length, n = grid[0].length;
UnionFind unionFind = new UnionFind(m * n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) { for (int k = j + 1; k < n; k++) { if (grid[i][k] == 1) { unionFind.union(toIndex(n, i, j), toIndex(n, i, k)); } } break; } } }
for (int j = 0; j < n; j++) { for (int i = 0; i < m; i++) { if (grid[i][j] == 1) { for (int k = i + 1; k < m; k++) { if (grid[k][j] == 1) { unionFind.union(toIndex(n, i, j), toIndex(n, k, j)); } } break; } } }
Map<Integer, Integer> rootToCountMap = new HashMap<>(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) { int root = unionFind.getRoot(toIndex(n, i, j)); rootToCountMap.put(root, rootToCountMap.getOrDefault(root, 0) + 1); } } }
int count = 0; for (int cellCount : rootToCountMap.values()) { if (cellCount > 1) { count += cellCount; } }
return count; }
private int toIndex(int n, int i, int j) { return i * n + j; } }
|