[LeetCode] Number of Black Blocks

2768. Number of Black Blocks

You are given two integers m and n representing the dimensions of a 0-indexed m x n grid.

You are also given a 0-indexed 2D integer matrix coordinates, where coordinates[i] = [x, y] indicates that the cell with coordinates [x, y] is colored black. All cells in the grid that do not appear in coordinates are white.

A block is defined as a 2 x 2 submatrix of the grid. More formally, a block with cell [x, y] as its top-left corner where 0 <= x < m - 1 and 0 <= y < n - 1 contains the coordinates [x, y], [x + 1, y], [x, y + 1], and [x + 1, y + 1].

Return a 0-indexed integer array arr of size 5 such that arr[i] is the number of blocks that contains exactly i *black cells*.

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
33
34
class Solution {
public:
vector<long long> countBlackBlocks(int m, int n, vector<vector<int>>& coordinates) {
vector<long long> res(5);
res[0] = 1ll * (m - 1) * (n - 1);
set<pair<long long, long long>> st;
set<pair<long long, long long>> blk;
auto push = [&](int x, int y) {
if(0 <= x and x < m - 1 and 0 <= y and y < n - 1) {
st.insert({x,y});
}
};
for(auto c : coordinates) {
int x = c[0], y = c[1];
push(x-1,y-1);
push(x-1,y);
push(x,y-1);
push(x,y);
blk.insert({x,y});
}
int dy[4]{0,1,0,1}, dx[4]{0,0,1,1};
for(auto& [x,y] : st) {
int cnt = 0;
for(int i = 0; i < 4; i++) {
int nx = x + dx[i], ny = y + dy[i];
if(blk.count({nx,ny})) cnt += 1;
}
res[0] -= 1;
res[cnt] += 1;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/09/PS/LeetCode/number-of-black-blocks/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.