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
  • 相关阅读:
    C#多线程学习笔记(三)——线程池
    html解析工具
    怎么样获取手机的主题
    我改进的《豆瓣搜》前后对比及源代码
    【收藏】Silverlight Style (二) 自定义样式在后台代码中应用
    C#多线程学习笔记(一)
    学习Linux——学习正确的思考方式(转)
    电信禁路由上网的破解方法
    印度软件业
    中国与印度软件工程师之比较
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13568697.html
Copyright © 2011-2022 走看看