[LeetCode] Lonely Pixel II

533. Lonely Pixel II

Given an m x n picture consisting of black ‘B’ and white ‘W’ pixels and an integer target, return the number of black lonely pixels.

A black lonely pixel is a character ‘B’ that located at a specific position (r, c) where:

  • Row r and column c both contain exactly target black pixels.
  • For all rows that have a black pixel at column c, they should be exactly the same as row r.
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
35
36
37
38
39
40
41
42
43
44
class Solution {
string toString(vector<char>& A) {
string res = "";
for(auto& a : A) res.push_back(a);
return res;
}
public:
int findBlackPixel(vector<vector<char>>& picture, int target) {
vector<string> P;
vector<int> rsum, csum;
for(auto& pic : picture) {
P.push_back(toString(pic));
int s = 0;
for(auto& pp : pic) s += pp == 'B';
rsum.push_back(s);
}
int n = picture.size(), m = picture[0].size(), res = 0;
unordered_map<int, vector<int>> mp;
for(int i = 0; i < m; i++) {
int s = 0;
for(int j = 0; j < n; j++) {
s += picture[j][i] == 'B';
if(picture[j][i] == 'B') mp[i].push_back(j);
}
csum.push_back(s);
}

for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(picture[i][j] == 'W') continue;
if(rsum[i] != target or csum[j] != target) continue;
bool pass = true;
for(auto& v : mp[j]) {
if(P[v] == P[i]) continue;
pass = false;
break;
}

res += pass;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/25/PS/LeetCode/lonely-pixel-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.