Verbose java solution using arrays


  • 0
    I
    public int findBlackPixel(char[][] picture, int N) {
        if (picture.length == 0 || picture[0].length == 0) {
            return 0;
        }
        int[] row = new int[picture.length];
        int[] col = new int[picture[0].length];
        int[] sameRowRoot = new int[picture.length];
        int[] sameRowCount = new int[picture.length];
        
        for (int i = 0; i < picture.length; i++) {
            sameRowRoot[i] = i;
            sameRowCount[i] = 1;
            for (int j = 0; j < picture[0].length; j++) {
                if (picture[i][j] == 'B') {
                    row[i]++;
                    col[j]++;
                }
            }
        }
    
        for (int i = 0; i < picture.length; i++) {
            for (int j = i + 1; j < picture.length; j++) {
                if (sameRowRoot[i] != i && sameRowRoot[j] != j) {
                    continue;
                }
                int k = 0;
                for (; k < picture[0].length; k++) {
                    if (picture[i][k] != picture[j][k]) {
                        break;
                    }
                }
                if (k == picture[0].length) {
                    sameRowRoot[j] = sameRowRoot[i];
                    sameRowCount[sameRowRoot[i]]++;
                }
            }
        }
        
        int res = 0;
        for (int i = 0; i < picture.length; i++) {
            if (sameRowCount[i] == N && row[i] == N) {
                for (int j = 0; j < picture[0].length; j++) {
                    if (picture[i][j] == 'B' && col[j] == N) {
                        res += N;
                    }
                }
            }
        }
        return res;
    }

Log in to reply
 

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