Daily Leetcode 695. Max Area of Island
https://leetcode.com/problems/max-area-of-island/
Medium
问题描述:
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:
1 | [[0,0,1,0,0,0,0,1,0,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:
1 | [[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.
题目分析:
给定一个由0、1
组成的二维数组,1
代表陆地,0
代表水域,上下左右相邻的1
可以视作是同一个岛屿,我们需要输出整个数组中面积最大的“岛屿”。
这一题可以通过深度优先遍历来寻找面积最大的岛, 在递归时,我们只需要考虑上下左右四种情况即可,需要注意的是,在遍历一个点后,我们需要将其置为0,以防止重复计算面积。
代码:
1 | class Solution(object): |