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]]

    Given the above grid, return 0.

    思路:

    里面:加起来,得出一个和

    外面:比较,双重for循环和所有点的和比较

    没想到的主要思路是:加一个1就消灭一个,记为0,各个击破。这是为了避免重复计算

    不是1的情况返回0

    if (grid[x][y] == 1)直接变成&,不需要嵌套

    class Solution {
        public int maxAreaOfIsland(int[][] grid) {
            //cc
            if (grid.length == 0 || grid[0].length == 0) {
                return 0;
            }
            
            int max = 0;
            
            //每一个点逐一比较
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[0].length; j++) {
                    max = Math.max(max, dfs(grid, i, j));
                }
            }
            
            return max;
        }
        
        //返回面积
        public int dfs(int[][] grid, int x, int y) {
            //标记
            if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && 
               grid[x][y] == 1) {             
                    grid[x][y] = 0;
                    
                    return 1 + dfs(grid, x - 1, y) + dfs(grid, x + 1, y) + 
                        dfs(grid, x, y - 1) + dfs(grid, x, y + 1);          
            }
            
            return 0;
        }
    }
    View Code
  • 相关阅读:
    SQL注入(转载)
    htmlTable To jpeg
    oracle 中文乱码 全变成 '靠'
    oracle 跨库查询
    oracle 备份还原数据库
    jquery 非异步读取数据
    oracle 游标 简单使用
    自增列的一种方法收藏
    oracle 导出txt 数据,excel 数据
    oracle 简单job
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13568697.html
Copyright © 2011-2022 走看看