Connected Cells in a Grid

  • + 0 comments

    With aux class so I can make a tupple without resorting to using stings and split():

    class OneSpot {
        int x;
        int y;
        public OneSpot(int x, int y) {
            this.x = x;
            this.y = y;
        }
        @Override
        public boolean equals(Object o) {
            OneSpot s = (OneSpot) o;
            return (s.x == x && s.y== y);
        }
        @Override
        public int hashCode() {
            return y * 100 + x;
        }
    }
    
    
    class Result {
    
        /*
         * Complete the 'connectedCell' function below.
         *
         * The function is expected to return an INTEGER.
         * The function accepts 2D_INTEGER_ARRAY matrix as parameter.
         */
        public static void grow(OneSpot spot, Set<OneSpot> ones, int xmax,
                                int ymax, Set<OneSpot> seen,
            Set<OneSpot> ourgang) {
                for (int dx = -1 ; dx < 2; dx++) {
                    for (int dy = -1; dy < 2; dy++) {
                        int nx = spot.x + dx;
                        int ny = spot.y + dy;
                        OneSpot nspot = new OneSpot(nx, ny);
                        if (ones.contains(nspot) && ! seen.contains(nspot)) {
                            ourgang.add(nspot);
                            seen.add(nspot);
                            grow(nspot, ones, xmax, ymax, seen, ourgang);
                        }
                    }
                }   
            }
    
        public static int connectedCell(List<List<Integer>> matrix) {
        // Write your code here
            Set<OneSpot> ones = new HashSet<>();
            int ymax = matrix.size() - 1;
            int xmax = matrix.get(0).size() - 1;
            for (int y = 0; y <= ymax; y++) {
                for (int x = 0; x <= xmax; x++) {
                    if (matrix.get(y).get(x) == 1) {
                        ones.add(new OneSpot(x, y));
                    }
                }
            }
            int size = 0;
            Set<OneSpot> seen = new HashSet<>();
            for (OneSpot spot : ones) {
                Set<OneSpot> ourgang = new HashSet<>();
                if (seen.contains(spot)) {
                    continue;
                }
                ourgang.add(spot);
                seen.add(spot);
                grow(spot, ones, xmax, ymax, seen, ourgang);
                if (ourgang.size() > size) {
                    size = ourgang.size();
                }
            }
            return size;
        }
    }