• Max Area of Island


    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

    Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

    Example 1:

    [[0,0,1,0,0,0,0,1,0,0,0,0,0],
     [0,0,0,0,0,0,0,1,1,1,0,0,0],
     [0,1,1,0,1,0,0,0,0,0,0,0,0],
     [0,1,0,0,1,1,0,0,1,0,1,0,0],
     [0,1,0,0,1,1,0,0,1,1,1,0,0],
     [0,0,0,0,0,0,0,0,0,0,1,0,0],
     [0,0,0,0,0,0,0,1,1,1,0,0,0],
     [0,0,0,0,0,0,0,1,1,0,0,0,0]]
    
    

    Given the above grid, return

    6
    

    . Note the answer is not 11, because the island must be connected 4-directionally.

    Example 2:

    [[0,0,0,0,0,0,0,0]]
    

    Given the above grid, return 0.

    Note: The length of each dimension in the given grid does not exceed 50.

    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            int max = 0;
            for (int i = 0; i < grid.length; i++) {
    			int[] js = grid[i];
    			for (int j = 0; j < js.length; j++) {
    				max = Math.max(max, island(grid, i, j));
    			}
    		}
            return max;
        }
        
        private static int island(int[][] grid,int x,int y){
    		if(x<0 || x>=grid.length || y<0 || y>=grid[x].length){
    			return 0;
    		}
    		int area = 0;
    		if(grid[x][y] == 1){
    			area=1;
    		}else{
    			return 0;
    		}
    		grid[x][y] = 0;
    		area += island(grid, x, y-1)+island(grid, x-1, y)+island(grid, x, y+1)+island(grid, x+1, y);
    		return area;
    	}
    }
    
  • 相关阅读:
    bzoj3751 / P2312 解方程
    P1270 “访问”美术馆(树形dp)
    [bzoj1085][SCOI2005]骑士精神
    [bzoj1208][HNOI2004]宠物收养所
    [bzoj1196][HNOI2006]公路修建问题
    [bzoj1093][ZJOI2007]最大半连通子图
    [bzoj1103][POI2007]大都市meg
    [Apio2009][bzoj1179]Atm
    [bzoj1191][HNOI2006]超级英雄Hero
    [bzoj2458][BeiJing2011]最小三角形
  • 原文地址:https://www.cnblogs.com/luozhiyun/p/8336404.html
Copyright © 2020-2023  润新知