Clean Java Solution Using 3 Arrays to Store Information


  • 0
    H

    The idea is simple, just using 3 arrays to store each row and column's black pixels' number as well as each row's description by concatenating all chars.

    class Solution {

    public int findBlackPixel(char[][] picture, int N) {
        if (picture == null || picture.length == 0 || picture[0] == null || picture[0].length == 0) return 0;
        int m = picture.length, n = picture[0].length;
        int[] horizontal = new int[m];
        int[] vertical = new int[n];
        String[] rows = new String[m];
        
        for (int i = 0; i < m; i++) {
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < n; j++) {
                sb.append(picture[i][j]);
                if (picture[i][j] == 'B') {
                    horizontal[i]++;
                    vertical[j]++;
                }
            }
            rows[i] = sb.toString();
        }
        
        int res = 0;
        for (int j = 0; j < n; j++) {
            if (vertical[j] != N) continue;
            String s = "";
            for (int i = 0; i < m; i++) {
                if (picture[i][j] == 'B'){
                    if (horizontal[i] != N || s.length() > 0 && !s.equals(rows[i])) {
                        s = "";
                        break;
                    }
                    
                    if (s.length() == 0) s = rows[i];
                }
            }
            if (s.length() > 0) res += N;
        }
        
        return res;
    }
    

    }


Log in to reply
 

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