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
    
    
    



     
  • 相关阅读:
    浅谈Linux文件操作
    数据结构学习--队列
    CODE[VS] 1099 字串变换
    CODE[VS] 1026 逃跑的拉尔夫
    CODE[VS] 3027 线段覆盖 2
    LeetCode8.字符串转换整数(atoi) JavaScript
    JS实现继承 JavaScript
    LeetCode7.整数反转 JavaScript
    LeetCode6.Z字形变换 JavaScript
    LeetCode5.最长回文子串 JavaScript
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13237021.html
Copyright © 2011-2022 走看看