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
    
    
    



     
  • 相关阅读:
    【C#】Send data between applications
    【C#】Switch datatype between object and byte[]
    【C#】Get the html code of a webpage
    MSIL Hello World
    MonoGame 3.2 下,截屏与 Texture2D 的保存
    mciSendString 的两个小坑
    virtual 修饰符与继承对析构函数的影响(C++)
    让 OpenAL 也支持 S16 Planar(辅以 FFmpeg)
    博客园第一篇——SDL2+FFmpeg 制作简单播放器&同步
    第五次UML作业——结对作业二:班级成绩表
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13237021.html
Copyright © 2011-2022 走看看