当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.695.Max Area of Island 岛屿的最大面积

LeetCode.695.Max Area of Island 岛屿的最大面积

题目描述

695 Max Area of Island
https://leetcode-cn.com/problems/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.

Note: The length of each dimension in the given grid does not exceed 50.


相似题目

LeetCode.695.Max Area of Island 岛屿的最大面积
LeetCode.200.Number of Islands 岛屿个数


解题过程

DFS深度优先搜索-递归

遍历二位数组,遇到 ‘1’ 就开始一次 深度优先搜索DFS ,每次dfs可遍历一座岛,dfs过程中将遍历过的结点设为’0’,并返回访问的1的个数,也就是岛的面积。

时间复杂度 O(mn) 空间复杂度 O(mn)

private static class SolutionV2020 {
    public int maxAreaOfIsland(int[][] grid) {
        if (null == grid || 0 == grid.length) {
            return 0;
        }
        int maxAres = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    int area = dfs(grid, i, j);
                    maxAres = Math.max(maxAres, area);
                }
            }
        }
        return maxAres;
    }

    // 从i,j开始深度优先搜索,返回访问的1的个数
    private int dfs(int[][] grid, int i, int j) {
        int rows = grid.length, columns = grid[0].length;
        int count = 0;
        if (grid[i][j] == 1) {
            grid[i][j] = 0;
            count++;
            if (i - 1 >= 0 && grid[i - 1][j] == 1) { // 上
                count += dfs(grid, i - 1, j);
            }
            if (j + 1 < columns && grid[i][j + 1] == 1) { // 右
                count += dfs(grid, i, j + 1);
            }
            if (i + 1 < rows && grid[i + 1][j] == 1) { // 下
                count += dfs(grid, i + 1, j);
            }
            if (j - 1 >= 0 && grid[i][j - 1] == 1) { // 左
                count += dfs(grid, i, j - 1);
            }
        }
        return count;
    }
}

GitHub代码

algorithms/leetcode/leetcode/_695_MaxAreaOfIsland.java
https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_695_MaxAreaOfIsland.java


上一篇 LeetCode.225.Implement Stack using Queues 用队列实现栈

下一篇 Hexo博客(29)ECharts图表展示网站访问量

阅读
评论
553
阅读预计3分钟
创建日期 2020-03-01
修改日期 2020-03-01
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论