题目:
Given a picture consisting of black and white pixels, find the number of black lonely pixels.
The picture is represented by a 2D char array consisting of 'B' and 'W', which means black and white pixels respectively.
A black lonely pixel is character 'B' that located at a specific position where the same row and same column don't have any other black pixels.
Example:
Input: [['W', 'W', 'B'], ['W', 'B', 'W'], ['B', 'W', 'W']] Output: 3 Explanation: All the three 'B's are black lonely pixels.
Note:
- The range of width and height of the input 2D array is [1,500].
思路:
可以记录下每个黑点的位置,以及每行、每列出现的黑点的个数。然后遍历每个黑点,如果发现它所在的行和列的黑点数都为1,那么它就是孤立黑点了。
代码:
class Solution {
public:
int findLonelyPixel(vector<vector<char>>& picture) {
if (picture.size() == 0 ||picture[0].size() == 0) {
return 0;
}
vector<int> row_pixels(picture.size(), 0);
vector<int> col_pixels(picture[0].size(), 0);
vector<pair<int, int>> black_positions;
for (int r = 0; r < picture.size(); ++r) {
for (int c = 0; c < picture[0].size(); ++c) {
if (picture[r][c] == 'B') {
black_positions.push_back(make_pair(r, c));
++row_pixels[r], ++col_pixels[c];
}
}
}
int ret = 0;
for (int i = 0; i < black_positions.size(); ++i) {
int r = black_positions[i].first, c = black_positions[i].second;
if (row_pixels[r] == 1 && col_pixels[c] == 1) {
++ret;
}
}
return ret;
}
};
这篇博客介绍了LeetCode上的第531题——找到图片中孤立的黑色像素点。文章阐述了问题背景,解释了一个黑点被认为是孤立的条件,并提供了解题思路。思路是通过记录黑点位置及行、列中黑点数量,遍历检查哪些黑点在同行同列中唯一。
620

被折叠的 条评论
为什么被折叠?



