Categories
Interview Questions

Making A Large Island

				
					class Solution {
    public int largestIsland(int[][] grid) {
        if (grid.length==0) return 0;
        Map<Integer,Integer> map = mapIslands(grid);
        int max = map.values().stream().reduce(Integer::max).get();
        for (int i = 0; i<grid.length; i++) {
            for (int j=0; j<grid[0].length;j++) {
                if (grid[i][j]==0) {
                    Map<Integer,Integer> seen = new HashMap<>();
                    seen.put(validGetColor(grid,i+1,j),map.get(validGetColor(grid,i+1,j)));
                    seen.put(validGetColor(grid,i-1,j),map.get(validGetColor(grid,i-1,j)));
                    seen.put(validGetColor(grid,i,j-1),map.get(validGetColor(grid,i,j-1)));
                    seen.put(validGetColor(grid,i,j+1),map.get(validGetColor(grid,i,j+1)));   
                    max = Math.max(max,seen.values().stream().reduce(0,Integer::sum)+1);
                }
            }
        }
        return max;
    }
    public Map<Integer,Integer> mapIslands(int[][] grid) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        int color = 2;
        map.put(-1,0);
        map.put(0,0);
        for (int i = 0; i<grid.length; i++) {
            for (int j=0; j<grid[0].length;j++) {
                if (grid[i][j]==1) 
                    map.put(color,explore(grid,i,j,color++));
            }
        }
        return map;
    }
    public int explore(int[][] grid, int i, int j,int color) {
        grid[i][j]=color;
        int count = 1;
        if (validGetColor(grid,i+1,j)==1) 
           count+=explore(grid,i+1,j,color);
        if (validGetColor(grid,i-1,j)==1) 
           count+=explore(grid,i-1,j,color);
        if (validGetColor(grid,i,j+1)==1) 
           count+=explore(grid,i,j+1,color);
        if (validGetColor(grid,i,j-1)==1) 
           count+=explore(grid,i,j-1,color);
        return count;
    }
    public int validGetColor(int[][] grid, int i, int j) {
        if (i>=grid.length || j>=grid[0].length || i<0 || j<0) return -1;
        return grid[i][j];
    }
}
				
			

Leave a Reply

Your email address will not be published. Required fields are marked *