• Time:Time:
• Space:Space:

## C++

``````class Solution {
public:
int countServers(vector<vector<int>>& grid) {
const int m = grid.size();
const int n = grid[0].size();
int ans = 0;
vector<int> rows(m);
vector<int> cols(n);

for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 1) {
++rows[i];
++cols[j];
}

for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1))
++ans;

return ans;
}
};
``````

## JAVA

``````class Solution {
public int countServers(int[][] grid) {
final int m = grid.length;
final int n = grid[0].length;
int ans = 0;
int[] rows = new int[m];
int[] cols = new int[n];

for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 1) {
++rows[i];
++cols[j];
}

for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1))
++ans;

return ans;
}
}
``````

## Python

``````class Solution:
def countServers(self, grid: List[List[int]]) -> int:
m = len(grid)
n = len(grid[0])
ans = 0
rows = [0] * m
cols = [0] * n

for i in range(m):
for j in range(n):
if grid[i][j] == 1:
rows[i] += 1
cols[j] += 1

for i in range(m):
for j in range(n):
if grid[i][j] == 1 and (rows[i] > 1 or cols[j] > 1):
ans += 1

return ans
``````