[Java] [C++] Clean Code with explanation


  • 4

    C++

    /**
     * suppose matrix is m*n, there is at most min(m, n) lonely pixels, because there could be no more than 1 in each row, or column;
     * therefore, if we record num of black pixel on each row and column, we can easily tell whether each pixel is lonely or NO.
     *     _0_1_2_
     *  0 | 0 0 1   rows[0] = 1
     *  1 | 0 1 0   rows[1] = 1
     *  2 | 1 0 0   rows[2] = 1
     * 
     * cols[0][1][2]
     *     1  1  1
     */
    class Solution {
    public:
        int findLonelyPixel(vector<vector<char>>& pic) {
            int m = pic.size();
            int n = pic[0].size();
            vector<int> rows = vector<int>(m, 0);
            vector<int> cols = vector<int>(n, 0);
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    rows[i] += pic[i][j] == 'B';
                    cols[j] += pic[i][j] == 'B';
                }
            }
            int lonely = 0;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n && rows[i] > 0; j++) {
                    lonely += pic[i][j] == 'B' && rows[i] == 1 && cols[j] == 1;
                }
            }
            return lonely;
        }
    };
    

    Java

    public class Solution {
        public int findLonelyPixel(char[][] pic) {
            int m = pic.length;
            int n = pic[0].length;
            int[] rows = new int[m];
            int[] cols = new int[n];
    
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    rows[i] += pic[i][j] == 'B' ? 1 : 0;
                    cols[j] += pic[i][j] == 'B' ? 1 : 0;
                }
            }
    
            int lonely = 0;
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n && rows[i] > 0; j++) {
                    lonely += (pic[i][j] == 'B' && rows[i] == 1 && cols[j] == 1) ? 1 : 0;
                }
            }
    
            return lonely;     
        }
    }
    

  • 0
    E
    This post is deleted!

Log in to reply
 

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