英文原题
You are given an m x n binary matrix grid. 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.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
1 | Input: grid = [[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]] |
分析
很经典的深度搜索题目,我的思路是遍历所有的点,发现有1以后去求这个岛屿的面积,用dfs,上下左右四个方向寻找,这里为了避免重复寻找,每找到一个1就把它变成0,看代码应该更直观。 第二次做这个题目了,上次做example还没有配图,这次居然有图了。
python 代码
1 | class Solution: |