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.length
n == grid[i].length
1 <= m <= 250
1 <= n <= 250
grid[i][j] == 0 or 1
Solution: Counting
Two passes:
First pass, count number of computers for each row and each column.
Second pass, count grid[i][j] if rows[i] or cols[j] has more than 1 computer.
Time complexity: O(m*n)
Space complexity: O(m + n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua class Solution { public: int countServers(vector<vector<int>>& grid) { const size_t m = grid.size(); const size_t n = grid[0].size(); vector<int> rows(m); vector<int> cols(n); for (size_t i = 0; i < m; ++i) for (size_t j = 0; j < n; ++j) { rows[i] += grid[i][j]; cols[j] += grid[i][j]; } int ans = 0; for (size_t i = 0; i < m; ++i) for (size_t j = 0; j < n; ++j) ans += (rows[i] > 1 || cols[j] > 1) ? grid[i][j] : 0; return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment