[LeetCode] 1267. Count Servers that Communicate 统计参与通信的服务器
作者:互联网
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
这道题说是在一个二维网格上有许多服务器,用数字1表示,这里定义了一种相连关系,若两个服务器同行或者同列就表示可以相互通信,现在问总共有多少个服务器可以和其他服务器进行通信。博主最先看到这题最先想到的就是简化版的N皇后问题 N-Queens,这里网格就相当于国际象棋棋盘,服务器就是皇后,只不过不能斜着走,只能横竖走(那其实就是国际象棋中的车 Rook)。不用走斜线就非常方便了,最简单粗暴的方法就是对于每个服务器,都遍历其他所有服务器,看是否同行或者同列。这种方法不是很高效,估计会超时,博主就没有写,来想想该怎么优化呢?
这道题的核心就是对于某个位置,快速查找是否有同行或者同列的其他点,可以用空间来换时间,由于并不需要知道同行或同列的点的具体位置,所以可以建立行数和在该行上的服务器个数之间的映射,同理建立列数和在该列上的服务器个数之间的映射。那么对于某个服务器的位置,只要用其行数去 HashMap 中查找,若映射值大于1个,则表示一定有另一个服务器在相同行上。否则再用列数去 HashMap 中查找,若映射值大于1个,则表示一定有另一个服务器在相同列上。只要找到同行或同列的服务器,结果 res 自增1即可,参见代码如下:
class Solution {
public:
int countServers(vector<vector<int>>& grid) {
int res = 0, m = grid.size(), n = grid[0].size();
unordered_map<int, int> rowCnt, colCnt;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) continue;
++rowCnt[i];
++colCnt[j];
}
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == 0) continue;
if (rowCnt[i] > 1 || colCnt[j] > 1) ++res;
}
}
return res;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1267
参考资料:
https://leetcode.com/problems/count-servers-that-communicate/
LeetCode All in One 题目讲解汇总(持续更新中...)
标签:Count,++,communicate,Communicate,1267,servers,grid,服务器,server 来源: https://www.cnblogs.com/grandyang/p/16178350.html