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
  • 相关阅读:
    SCXML和QScxml使用总结
    qt 使用qtxlsx 读写excel
    Qt Qml嵌入Widget以及Qml与Widget交互
    三步带你开发一个短链接生成平台
    SessionStorage、LocalStorage详解
    低代码如何支撑企业级应用开发?
    开发一个渐进式Web应用程序(PWA)前都需要了解什么?
    详细了解JS Map,它和传统对象有什么区别?
    5种可能在10年后消失的开发语言
    更改tomcat启动的端口号
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13568697.html
Copyright © 2011-2022 走看看