Count Servers that Communicate

medium array matrix counting

Problem

You are given an m × n grid where each cell holds 1 for a server or 0 for empty space. Two servers communicate when they share the same row or the same column. Return how many servers can communicate with at least one other server.

Inputgrid = [[1, 0], [1, 1]]
Output3
Server (0,0) shares column 0 with (1,0). The two servers in row 1, (1,0) and (1,1), share that row. All three communicate, so the answer is 3.

def count_servers(grid):
    R, C = len(grid), len(grid[0])
    row = [sum(r) for r in grid]
    col = [sum(grid[i][j] for i in range(R)) for j in range(C)]
    total = 0
    for i in range(R):
        for j in range(C):
            if grid[i][j] == 1 and (row[i] > 1 or col[j] > 1):
                total += 1
    return total
function countServers(grid) {
  const R = grid.length, C = grid[0].length;
  const row = new Array(R).fill(0), col = new Array(C).fill(0);
  for (let i = 0; i < R; i++) for (let j = 0; j < C; j++) if (grid[i][j] === 1) { row[i]++; col[j]++; }
  let total = 0;
  for (let i = 0; i < R; i++) for (let j = 0; j < C; j++)
    if (grid[i][j] === 1 && (row[i] > 1 || col[j] > 1)) total++;
  return total;
}
class Solution {
    public int countServers(int[][] grid) {
        int R = grid.length, C = grid[0].length;
        int[] row = new int[R], col = new int[C];
        for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (grid[i][j] == 1) { row[i]++; col[j]++; }
        int total = 0;
        for (int i = 0; i < R; i++) for (int j = 0; j < C; j++)
            if (grid[i][j] == 1 && (row[i] > 1 || col[j] > 1)) total++;
        return total;
    }
}
int countServers(vector<vector<int>>& grid) {
    int R = grid.size(), C = grid[0].size();
    vector<int> row(R), col(C);
    for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (grid[i][j] == 1) { row[i]++; col[j]++; }
    int total = 0;
    for (int i = 0; i < R; i++) for (int j = 0; j < C; j++)
        if (grid[i][j] == 1 && (row[i] > 1 || col[j] > 1)) total++;
    return total;
}
Time: O(R·C) Space: O(R+C)