1. Description
An m x n matrix grid represents a server center: 1 indicates a server, and 0 indicates an empty cell.
Two servers can communicate when they share a row or column, regardless of the distance between them.
Return how many servers can communicate with at least one other server, counting each server once.
2. Example
Example 1
Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: The two servers occupy different rows and columns, so neither can communicate.
Example 2
Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: Each server shares a row or column with another server, so all three are counted.
Example 3
Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: Two servers share the first row, and two share the third column. The bottom-right server is isolated.
3. Constraints
- m == grid.length
- n == grid[i].length
- 1 <= m <= 250
- 1 <= n <= 250
- grid[i][j] is either 0 or 1.
4. Solutions
Counting with In-place Marking
m = grid.size(), n = grid.front().size()
Time complexity: O(mn)
Space complexity: O(n)
| |