zoukankan      html  css  js  c++  java
  • 695. 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]]

    思路:加一个1就消灭一个,记为0,各个击破。消灭了就消灭了,联通的一个岛统计一次也就够了

    要限制范围在数组的length以内,如果不符合条件就返回0

    还要逐个比较max = max(max, value)得出最大值

    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            //corner case
            if (grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            //compare all areas
            int max = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    max = Math.max(max, areaOfIsland(i, j, grid));
                }
            }
            return max;
        }
        
        public int areaOfIsland(int i, int j, int[][] grid) {
            //valid first, == 1 second
        if (0 <= i && i < grid.length && 0<= j && j < grid[0].length && grid[i][j] == 1) {
            //restore to 0 to avoid repeat
            grid[i][j] = 0;
            //count area
            return 1 + areaOfIsland(i - 1, j, grid) + areaOfIsland(i + 1, j, grid) + areaOfIsland(i, j - 1, grid) + areaOfIsland(i, j + 1, grid);
        }
            //if not 1, default case : return 0
            return 0;
        }
    }
    View Code
    
    
    



     
  • 相关阅读:
    CentOS7.5右键创建空白文档
    CentOS7.5安装配置conky(极简)
    CentOS7.5安装nodejs
    CentOS7.5安装网易云音乐
    CentOS7.5删除旧的内核
    CentOS7.5安装notepadqq
    CentOS7英文环境下使用中文输入法
    CentOS7安装Pycharm后无法使用日常的快捷键
    tomcat的work目录作用
    ORACLE获取某个时间段之间的月份列表
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13237021.html
Copyright © 2011-2022 走看看