To solve the problem, I used an approach based on counting the number of servers in each row and column. First, I traversed the grid to calculate two arrays: row_count
and col_count
. row_count[i]
stores the number of servers in row i
, and col_count[j]
stores the number of servers in column j
.
Next, I performed a second traversal of the grid. For each server (grid[i][j] == 1
), I checked if there were other servers in its row or column by evaluating whether row_count[i] > 1
or col_count[j] > 1
. If either condition was true, the server was added to the count of communicating servers - res
.
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
row_count = [0] * m
col_count = [0] * n
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
row_count[i] += 1
col_count[j] += 1
res = 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):
res += 1
return res
- Time: O(m * n)
- Space: O(m * n
