1. Title Description
You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Return the number of servers that communicate with any other server.
Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Second, the solution
Method 1: Enumeration
- Two or more computers must be in the same row and column to communicate with each other.
- That is to say, if there is only one PC in the row and column of a certain location, they cannot communicate with each other.
public int countServers(int[][] grid) {
int R = grid.length, C = grid[0].length;
int[] row = new int[R];
int[] col = new int[C];
int res = 0;
for (int x = 0; x < R; x++)
for (int y = 0; y < C; y++) {
if (grid[x][y] == 1) {
row[x]++; col[y]++;
res++;
}
}
for (int x = 0; x < R; x++)
for (int y = 0; y < C; y++) {
if (grid[x][y] == 1 && row[x] == 1 && col[y] == 1) {
res--;
}
}
return res;
}
Complexity analysis
- time complexity: ,
- Space complexity: ,
Method 2: Check
- If a certain grid is encountered, then merge the row and column where it is, and
count++
. - Finally, find only one child under a certain node in the parallel search set uf. If there is, prove that this pc is independent
count--
.
Q&A
- Q1: Why are the merged rows and columns
union(i, j+row)
?
A1, wrong interpretation : the rectangle has m rows and n columns, but the id array of the check set has only one row, so represents an array id values are shown, where itj + m
represents the i-th row j-th column of the array index id.
int R, C;
public int countServers(int[][] grid) {
R = grid.length; C = grid[0].length;
int tot = 0;
UF uf = new UF(R + C);
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++) {
if (grid[i][j] == 1) {
tot++;
uf.union(i, j+R);
}
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++) {
if (grid[i][j] == 1) {
int p = uf.find(i);
map.put(p, map.getOrDefault(p, 0)+1);
}
}
for (int k : map.keySet()) {
if (map.get(k) == 1)
tot--;
}
return tot;
}
class UF {
int[] id;
int count;
public UF(int N) {
id = new int[N];
for (int i = 0; i < N; i++) {
id[i] = i;
}
}
public int find(int p) {
while (p != id[p]) {
p = id[p];
}
return p;
}
public boolean isConn(int p, int q) {
return find(p) == find(q);
}
public void union(int p, int q) {
int pID = find(p);
int qID = find(q);
if (pID == qID) {
return;
}
id[pID] = qID;
count--;
}
}
Complexity analysis
- time complexity: ,
- Space complexity: ,