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
    
    
    



     
  • 相关阅读:
    Nosql介绍
    linux系统安装mysql
    linux下装tomcat教程
    linux系统下安装jdk教程
    XML解析
    XML 可扩展标记语言
    Oracle——子查询
    数据库——Oracle(增删改查,单行函数,多行函数,多表查询)
    Ubuntu16.04Scrapy爬虫定时任务
    大数据——zookeeper分布式集群管理工具的学习与使用
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13237021.html
Copyright © 2011-2022 走看看