leetcode 1267. Count Servers that Communicate

时间:2019-11-25 16:31:48   收藏:0   阅读:76

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:

 1 class Solution {
 2 public:
 3     int countServers(vector<vector<int>>& grid) {
 4         vector<int> row(grid.size(), 0), col(grid[0].size(), 0);
 5         for (int i = 0; i < grid.size(); ++i) {
 6             for (int j = 0; j < grid[0].size(); ++j) {
 7                 if (grid[i][j] == 1) {
 8                     row[i]++;
 9                     col[j]++;
10                 }
11             }
12         }
13         int cnt = 0;
14         for (int i = 0; i < grid.size(); ++i) {
15             for (int j = 0; j < grid[0].size(); ++j) {
16                 if ((grid[i][j] == 1) && (row[i] > 1 || col[j] > 1))
17                     cnt++;
18             }
19         }
20         return cnt;
21     }
22 };

 

原文:https://www.cnblogs.com/qinduanyinghua/p/11928400.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!