C++ 39ms solution no map no redundant comparison


  • 0
    H
    class Solution {
    public:
        int findBlackPixel(vector<vector<char>>& picture, int N) {
            int res = 0;
            int m = picture.size();
            if (m == 0) return res;
            int n = picture[0].size();
            vector<int> row(m, 0), col(n, 0);
            vector<string> rows(m);
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    rows[i].push_back(picture[i][j]);
                    if (picture[i][j] == 'B') {
                        row[i]++;
                        col[j]++;
                    }
                }
            }
            for (int i = 0; i < m; i++) {
                if (row[i] != N) continue;
                for (int j = 0; j < n; j++) {
                    if (picture[i][j] == 'B' && col[j] == N) {
                        bool valid = true;
                        for (int k = 0; k < m; k++) {
                            if (picture[k][j] == 'B' && rows[k] != rows[i]){
                                valid = false;
                                break;
                            }
                        }
                        if (valid) {
                            res += N; // all these N rows are valid answer
                            // reset this column to 0 to avoid recalculation 
                            //for other rows which have been covered in this loop
                            col[j] = 0; 
                        }
                    }
                }
            }
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.