Java Solution using HashMap


  • 0
    Z

    Hi there! My solution is quite strightforward. I will just live it there:=)

    public class Solution {
        public int findBlackPixel(char[][] picture, int N) {
            if(picture == null || picture.length == 0 || picture[0].length == 0) return 0;
            Map<String, Set<Integer>> simMap = new HashMap<>();
            for(int row = 0;row<picture.length;row++){
                String hash = getRowHash(picture,row);
                Set<Integer> simRows = simMap.getOrDefault(hash, new HashSet<>());
                simRows.add(row);
                simMap.put(hash, simRows);
            }
            int [] rowBlacks = new int[picture.length];
            for(int row = 0;row<picture.length;row++){
                rowBlacks[row] = getRowBlackNum(picture, row);
            }
            List<Integer> colBlacks[] = new List[picture[0].length];
            for(int col = 0;col<picture[0].length;col++){
                colBlacks[col]= getColBlackRows(picture, col);
            }
            int res= 0;
            for(int row = 0;row<picture.length;row++){
                if(rowBlacks[row] == N){
                    String hash = getRowHash(picture, row);
                    for(int col = 0;col<picture[row].length;col++){
                        if(picture[row][col] == 'B' && colBlacks[col].size() == N){
                            boolean consists = true;
                            for(int r:colBlacks[col]){
                                consists =consists && simMap.containsKey(hash) && simMap.get(hash).contains(r);
                            }
                            if(consists) res++;
                        }
                    }
                }
            }
            return res;
        }
        
        private int getRowBlackNum(char [][] picture, int row){
            int res=  0;
            for(int col = 0;col<picture[0].length;col++){
                if(picture[row][col] == 'B') res++;
            }
            return res;
        }
        
        private List<Integer> getColBlackRows(char [][] picture, int col){
            List<Integer> res=  new ArrayList<>();
            for(int row = 0;row<picture.length;row++){
                if(picture[row][col] == 'B') res.add(row);
            }
            return res;
        }
        
        private String getRowHash(char [][] picture, int row){
            return new String(picture[row]);
        }
    }

Log in to reply
 

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