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 1The problem can be solved by counting the servers in each row and column. If a server's row or column has more than one server, it can communicate with another server. Therefore, the solution consists of counting the number of servers in each row and column and then checking whether each server can communicate.
This solution uses a two-pass approach. The first pass populates the row_count and col_count arrays, which store the count of servers in each row and column respectively. The second pass checks for each server if it can communicate with any other server and increments the count accordingly.
Java
C++
C
C#
JavaScript
Time Complexity: O(m * n) where m is the number of rows and n is the number of columns.
Space Complexity: O(m + n) for storing row and column counts.
The problem can alternatively be approached by directly traversing the matrix once, using auxiliary data structures to maintain counts of rows and columns. This helps in determining if a server at any particular cell can communicate by inspecting these counts directly.
This approach uses Python's defaultdict to dynamically store and access the count of servers in rows and columns, allowing efficient traversal and checking within the grid.
Java
C++
C
C#
JavaScript
Time Complexity: O(m * n) for traversal.
Space Complexity: O(m + n) for auxiliary storage of counts.
| Approach | Complexity |
|---|---|
| Row and Column Count | Time Complexity: O(m * n) where m is the number of rows and n is the number of columns. |
| Matrix Traversal | Time Complexity: O(m * n) for traversal. |
Count Servers that Communicate - Leetcode 1267 - Python • NeetCodeIO • 8,362 views views
Watch 9 more video solutions →Practice Count Servers that Communicate with our built-in code editor and test cases.
Practice on FleetCode