zoukankan      html  css  js  c++  java
  • 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.)

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/max-area-of-island
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    =================================================================

    求岛屿的最大面积,我们可以通过DFS的方法来做。当遍历到“1”时,证明存在岛屿,所以可以以此为起点,向周围扩散,以期遍历到更多的“1”。每遇到一个“1”,岛屿的面积可以+1,同时,这个“1”也应该标记起来,证明该岛屿已经把这个“1”计算在内。直到这个岛屿周围全都是“0”,即已经被水包围时,证明当前岛屿的面积计算已经到达最大值,那么可以与暂存的Max(遇到的岛屿面积的最大值)相比较并适时更新。当二维数组中已经不存在未被访问过的“1”时,说明地图上所有的岛屿都已被探索出,可返回最终的结果值。

    实现代码:

    class Solution {
        static int[] dx = {-1, 1, 0, 0};
        static int[] dy = {0, 0, -1, 1};
        static int rows, cols, curArea;
        public int maxAreaOfIsland(int[][] grid) {
            rows = grid.length;
            cols = grid[0].length;
            int Max = 0;
            for(int r = 0; r < rows; r++) {
                for(int c = 0; c < cols; c++) {
                    if(grid[r][c] == 1) {
                        curArea = 0;
                        DFS(grid, r, c);
                        Max = Max > curArea ? Max : curArea;
                    }
                }
            }
            return Max;
        }
    
        public static void DFS(int[][] grid, int r, int c) {
            curArea++;
            grid[r][c] = 0;
            for(int i = 0; i < 4; i++) {
                int x = r + dx[i];
                int y = c + dy[i];
                if(x >= 0 && x < rows && y >= 0 && y < cols) {
                    if(grid[x][y] == 1)
                        DFS(grid, x, y);
                }
            }
        }
    }
  • 相关阅读:
    Arduino mega 2560驱动安装失败(没有建立对验证码(TM)签名的目录的发布者信任)的解决方法
    Submile text3 安装使用技巧
    window.onload
    JS简单示例
    python类和对象的底层实现
    python类中方法加单下划线、双下划线、前后双下滑线的区别
    linux下json工具jq
    Django使用自定义的authentication登录认证
    django admin
    linux网卡桥接问题与docker网卡桥接问题
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/13030943.html
Copyright © 2011-2022 走看看