[Leetcode] 531. Lonely Pixel I 解题报告

这篇博客介绍了LeetCode上的第531题——找到图片中孤立的黑色像素点。文章阐述了问题背景,解释了一个黑点被认为是孤立的条件,并提供了解题思路。思路是通过记录黑点位置及行、列中黑点数量,遍历检查哪些黑点在同行同列中唯一。

题目

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:

  1. 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值