package hackerrank.ctci;

import java.util.Scanner;

/**
 * https://www.hackerrank.com/challenges/ctci-connected-cell-in-a-grid
 */
public class ConnectedCellInAGrid {
    private static int connectedCell(int[][] grid) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        int grid[][] = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                grid[i][j] = in.nextInt();
            }
        }
    }
}

@@ -214,44 +214,1726 @@
 grid
-) %7B%0A        // TODO%0A        return 0
+, int maxRow, int maxCol) %7B%0A        boolean%5B%5D%5B%5D marked = new boolean%5BmaxRow%5D%5BmaxCol%5D;%0A        int max = 0;%0A        for (int row = 0; row %3C maxRow; row++) %7B%0A            for (int col = 0; col %3C maxCol; col++) %7B%0A                if (grid%5Brow%5D%5Bcol%5D == 1 && !marked%5Brow%5D%5Bcol%5D) %7B%0A                    max = Math.max(max, connectedCell(grid, marked, row, col, maxRow, maxCol));%0A                %7D%0A            %7D%0A        %7D%0A        return max;%0A    %7D%0A%0A    private static int connectedCell(int%5B%5D%5B%5D grid, boolean%5B%5D%5B%5D marked,%0A                                      int row, int col, int maxRow, int maxCol) %7B%0A        if (row %3C 0 %7C%7C row %3E= maxRow %7C%7C col %3C 0 %7C%7C col %3E= maxCol) %7B%0A            return 0;%0A        %7D%0A        if (marked%5Brow%5D%5Bcol%5D %7C%7C grid%5Brow%5D%5Bcol%5D == 0) %7B%0A            return 0;%0A        %7D%0A        int val = 0;%0A        if (grid%5Brow%5D%5Bcol%5D == 1) %7B%0A            val = 1;%0A        %7D%0A        marked%5Brow%5D%5Bcol%5D = true;%0A        // top%0A        int a = connectedCell(grid, marked, row - 1, col, maxRow, maxCol);%0A        // top right%0A        int b = connectedCell(grid, marked, row - 1, col + 1, maxRow, maxCol);%0A        // right%0A        int c = connectedCell(grid, marked, row, col + 1, maxRow, maxCol);%0A        // bottom right%0A        int d = connectedCell(grid, marked, row + 1, col + 1, maxRow, maxCol);%0A        // bottom%0A        int e = connectedCell(grid, marked, row + 1, col, maxRow, maxCol);%0A        // bottom left%0A        int f = connectedCell(grid, marked, row + 1, col - 1, maxRow, maxCol);%0A        // left%0A        int g = connectedCell(grid, marked, row, col - 1, maxRow, maxCol);%0A        // top left%0A        int h = connectedCell(grid, marked, row - 1, col - 1, maxRow, maxCol);%0A        return val + a + b + c + d + e + f + g + h
 ;%0A  
@@ -2254,32 +2254,32 @@
 ;%0A            %7D%0A
-
         %7D%0A    %7D%0A
@@ -2268,20 +2268,75 @@
 %7D%0A        %7D%0A
+        System.out.println(connectedCell(grid, n, m));%0A
     %7D%0A%7D%0A

Solve Connected Cell In A Grid