Java Solution using HashMaps


  • 0
    public class Solution {
        public int findBlackPixel(char[][] picture, int N) {
            int res = 0;
            Map<Integer, List<Integer>> colMap = new HashMap<Integer, List<Integer>>();
            Map<Integer, List<Integer>> rowMap = new HashMap<Integer, List<Integer>>();
            Map<Integer, String> matchMap = new HashMap<Integer, String>();
            for (int i = 0; i < picture.length; i++) {
                for (int j = 0; j < picture[0].length; j++) {
                    if (picture[i][j] == 'B') {
                        if (!rowMap.containsKey(i)) {
                            rowMap.put(i, new ArrayList<Integer>());
                        }
                        if (!colMap.containsKey(j)) {
                            colMap.put(j, new ArrayList<Integer>());
                        }
                        rowMap.get(i).add(j);
                        colMap.get(j).add(i);
                        matchMap.put(i, matchMap.getOrDefault(i, "") + "," + j);
                    }
                }
            }
    
            for (int i = 0; i < picture.length; i++) {
                for (int j = 0; j < picture[0].length; j++) {
                    if (picture[i][j] == 'B' && rowMap.get(i).size() == N && colMap.get(j).size() == N) {
                        List<Integer> rowsList = colMap.get(j);
                        String key = matchMap.get(rowsList.get(0));
                        int count = 1;
                        for (int k = 1; k < rowsList.size(); k++) {
                            if (key.equals(matchMap.get(rowsList.get(k)))) {
                                count++;
                            } else {
                                break;
                            }
                        }
                        if (count == N) {
                            res++;
                        }
                    }
                }
            }
            return res;
        }
    }
    

Log in to reply
 

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