Count Servers that Communicate Problem
Description
LeetCode Problem 1267.
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.
Example 2:

Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.
Example 3:

Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.
Constraints:
m == grid.lengthn == grid[i].length1 <= m <= 2501 <= n <= 250grid[i][j] == 0 or 1
Solution
Approach: Count Servers per Row and Column
A server communicates if at least one other server is in its row or in its column. We do not need to know which one, only how many servers each row and each column holds.
- In a first pass over the grid, count the servers in every row (
rowCount) and every column (colCount). - In a second pass, a server at
(i, j)communicates exactly whenrowCount[i] > 1orcolCount[j] > 1: the count includes the server itself, so more than one means someone else is there too.
Each server is counted once even when it shares both its row and its column with others, because we check each cell only once and add 1 for it.
Complexity: O(m·n) time for an m x n grid, and O(m + n) extra space for the two count arrays.
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
row_count = [0] * m # servers in each row
col_count = [0] * n # servers in each column
for i in range(m):
for j in range(n):
row_count[i] += grid[i][j]
col_count[j] += grid[i][j]
answer = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1 and (row_count[i] > 1 or col_count[j] > 1):
answer += 1
return answer