531. Lonely Pixel I

https://leetcode.com/problems/lonely-pixel-i/description/

The gist of the title: Given a rectangle consisting of the characters 'W' and 'B', w stands for blank, b stands for pixel, find out the total number of pixels in the matrix with only one pixel of itself in the horizontal and vertical directions. Problem-
solving idea: traverse the matrix twice .The first time the pixel number table rows, cols in the horizontal and vertical directions are established, and the second time is based on the data in the table, if the position of a[i, j] is a pixel, and rows[i], cols[j] are both equal to 1, then the Pixel conforms.
A trick is used here. In the second traversal, when the inner layer j loops, adding restrictions on i rows[i]>0can reduce the unnecessary traversal of j.

Code:

class Solution {
public:
    int findLonelyPixel(vector<vector<char>>& picture) {
        int m = picture.size();  //行数
        int n = picture[0].size();  //列数
        vector<int> rows(m);
        vector<int> cols(n);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (picture[i][j] == 'B') {
                    rows[i]++; 
                    cols[j]++;
                }
            }
        }
        int res = 0;
        for (int i = 0; i < m ; i++) {  //遍历每行
             for (int j = 0; j < n && rows[i] > 0; j++)   {  //小trick,只遍历rows[i] > 0的列
                 if (picture[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) res++;
             }
        }
        return res;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325698585&siteId=291194637