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

来源:互联网 发布:java list方法 编辑:程序博客网 时间:2024/06/05 08:04

题目

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: 3Explanation: 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;    }};

原创粉丝点击