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.
Example 1:
Input: grid = [[1,0],[0,1]] Output: 0 Explanation: No servers can communicate with others.
思路:用rowcount和colcount来计数,只要遇见1,server就+1,这里tricky的地方是做减法,如果rowcount和colcount都只是1,说明这个机器没有connect,server--;
class Solution {
public int countServers(int[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int n = grid.length;
int m = grid[0].length;
int[] rowcount = new int[n];
int[] colcount = new int[m];
int server = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == 1) {
rowcount[i]++;
colcount[j]++;
server++;
}
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == 1 && rowcount[i] == 1 && colcount[j] == 1) {
server--;
}
}
}
return server;
}
}