Count Servers that Communicate

给一个2d的0,1数组, 每个点表示一个服务器, 它的列和行上有其他服务器就Communicate, 问有多少个. 先记录一下每行有几个, 每列有几个, 然后就直接写就出来了.

class Solution {
    public int countServers(int[][] grid) {
        int count = 0;
        int n = grid.length;
        int m = grid[0].length;
        int[] r = new int[n]; // count the number of 1 in each row
        int[] c = new int[m]; // count the number of 1 in each col
        
        for(int i = 0 ; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(grid[i][j] == 1) {
                  r[i] ++;
                  c[j] ++;
                }
            }
        }
                
        for(int i = 0 ; i < n; i++) {
            for(int j = 0; j < m; j++) {
                if(grid[i][j] == 1) {
                    if(r[i] > 1 || c[j] > 1) // if it is not alone
                        count++;
                }
            }
        }
        
        return count;
    }
}