Problem Description
Given a grid representing a server center (where 1 indicates a server and 0 indicates no server), two servers communicate if they are in the same row or column. Return the number of servers that can communicate with at least one other server.
Key Insights
- A server can communicate only if there is at least one other server in its row or column.
- Count the total servers present per row and per column.
- In a subsequent pass, verify for each server that its corresponding row or column has more than one server.
- This two-pass method ensures an efficient solution.
Space and Time Complexity
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 counts for rows and columns.
Solution
The solution uses a two-pass approach:
- First pass: Traverse the grid to count the number of servers in each row and column using simple arrays.
- Second pass: For every cell containing a server, check if the corresponding row or column has a count greater than one. If so, count that server as communicating. This approach efficiently leverages the grid structure with a linear scan and minimal extra space.