[LeetCode] Count Servers that Communicate

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
int countServers(vector<vector<int>>& A) {
int n = A.size(), m = A[0].size();
unordered_map<int, vector<int>> row;
unordered_map<int, vector<int>> col;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(A[i][j]) {
row[i].push_back(j);
col[j].push_back(i);
}
}
}
int res = 0;
for(auto& [y, vx] : row) {
if(vx.size() == 1) continue;
for(auto& x : vx) {
res += A[y][x];
A[y][x] = 0;
}
}
for(auto& [x, vy] : col) {
if(vy.size() == 1) continue;
for(auto& y : vy) {
res += A[y][x];
A[y][x] = 0;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/01/PS/LeetCode/count-servers-that-communicate/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.