[LeetCode] Count Covered Buildings

3531. Count Covered Buildings

You are given a positive integer n, representing an n x n city. You are also given a 2D grid buildings, where buildings[i] = [x, y] denotes a unique building located at coordinates [x, y].

A building is covered if there is at least one building in all four directions: left, right, above, and below.

Return the number of covered buildings.

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
class Solution {
public:
int countCoveredBuildings(int n, vector<vector<int>>& buildings) {
unordered_map<int,pair<int,int>> ymp, xmp;
auto push = [](unordered_map<int,pair<int,int>>& mp, int key, int val) {
if(!mp.count(key)) mp[key] = {val, val};
else {
mp[key].first = min(mp[key].first, val);
mp[key].second = max(mp[key].second, val);
}
};
for(auto& b : buildings) {
int y = b[0], x = b[1];
push(ymp, y, x);
push(xmp, x, y);
}
int res = 0;
auto ok = [](unordered_map<int,pair<int,int>>& mp, int key, int val) {
auto [l,r] = mp[key];
return l < val and val < r;
};
for(auto& b : buildings) {
int y = b[0], x = b[1];
res += ok(ymp, y, x) and ok(xmp, x, y);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2025/04/27/PS/LeetCode/count-covered-buildings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.