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);
                }
            }
        }
    }
  • 相关阅读:
    ASP.NET AJAX Sys未定义的解决方法
    网页简繁体转换
    asp.net2.0中TreeView不刷新获得节点值
    异常详细信息: System.Runtime.InteropServices.COMException: 无效的类别字符串
    HDOJ1233 还是畅通工程[Prim算法||Kruskal算法]
    Kruskal/Prim/Dijkstra模板
    HDOJ3790 最短路径问题[Dijkstra算法||SPFA]
    HDOJ1285 确定比赛名次[拓扑排序]
    HDOJ1162 Eddy's picture[求最短路prim||kruskal算法]
    HDOJ1213 How Many Tables[并查集入门]
  • 原文地址:https://www.cnblogs.com/WakingShaw/p/13030943.html
Copyright © 2011-2022 走看看