LeetCode刷题实战533: 孤独像素 II
Given a picture consisting of black and white pixels, and a positive integer N, find the number of black pixels located at some specific row R and column C that align with all the following rules:
Row R and column C both contain exactly N black pixels.
For all rows that have a black pixel at column C, they should be exactly the same as row R
The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively.
行R 和列C都恰好包括N个黑色像素。
列C中所有黑色像素所在的行必须和行R完全相同。
示例
示例:
输入:
[['W', 'B', 'W', 'B', 'B', 'W'],
['W', 'B', 'W', 'B', 'B', 'W'],
['W', 'B', 'W', 'B', 'B', 'W'],
['W', 'W', 'B', 'W', 'B', 'W']]
N = 3
输出: 6
解析: 所有粗体的'B'都是我们所求的像素(第1列和第3列的所有'B').
0 1 2 3 4 5 列号
0 [['W', 'B', 'W', 'B', 'B', 'W'],
1 ['W', 'B', 'W', 'B', 'B', 'W'],
2 ['W', 'B', 'W', 'B', 'B', 'W'],
3 ['W', 'W', 'B', 'W', 'B', 'W']]
行号
以R = 0行和C = 1列的'B'为例:
规则 1,R = 0行和C = 1列都恰好有N = 3个黑色像素.
规则 2,在C = 1列的黑色像素分别位于0,1和2行。它们都和R = 0行完全相同。
注意:
输入二维数组行和列的范围是 [1,200]。
解题
class Solution {
public:
int findBlackPixel(vector<vector<char>>& picture, int N) {
vector<int> rows(picture.size(),0);
vector<int> cols(picture[0].size(),0);
//统计各行和各列的B的数量
for(int i=0;ifor(int j=0;j 0].size();++j){
if(picture[i][j]=='B'){
++rows[i];
++cols[j];
}
}
}
int res=0;
//再次遍历一遍进行判断
for(int i=0;ifor(int j=0;j 0].size();++j){
//当前字符是B,且对应的行和列的数量是给出的N,说明满足第一个条件
if(picture[i][j]=='B'&&rows[i]==N&&cols[j]==N){
//先统计出列对应的各个行是哪些
vector<int> tmp;
for(int k=0;kif(picture[k][j]=='B'){
tmp.push_back(k);
}
}
//判断列对应的各个行是否相同,既是否满足第二个条件
int pos=1;
while(posif(picture[tmp[0]]!=picture[tmp[pos]]){
break;
}
++pos;
}
//若满足,则增加统计
if(pos==tmp.size()){
++res;
}
}
}
}
return res;
}
};
