题目
给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
示例一
[[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]]
对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。
示例二
[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回 0。
注意: 给定的矩阵grid
的长度和宽度都不超过 50。
分析与解答
这道题目和前面做过的python-数据结构 岛屿的个数 深度优先 广度优先 两种解答是一个一模一样的题目,主要是可以使用队列来进行一个广度优先查询。
class Solution:
def maxAreaOfIsland(self, grid) -> int:
if not grid:
return 0
if isinstance(grid[0], bool) or isinstance(grid[0], int):
return 1 if grid[0] else 0
ilsand_list = [0] # 排除当没有岛屿的时候,执行max函数出错
m, n = len(grid), len(grid[0]) # m代表行, n代表列
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
grid[i][j] = "0"
size_of_island, grid = self.get_size_of_island(i, j, grid) # 利用队列(广度优先查询),将岛屿所在位置全部求出并且获得岛屿大小
ilsand_list.append(size_of_island)
return max(ilsand_list)
def get_size_of_island(self, i, j, grid):
size_of_island = 1 # 能走到这边说明这个岛屿的最小初始面积为1
m, n = len(grid), len(grid[0]) # m代表行, n代表列
use_list = [[i, j], ]
while len(use_list):
i, j = use_list.pop(0)
if i > 0:
if grid[i - 1][j] == 1:
grid[i - 1][j] = "0"
use_list.append([i - 1, j])
size_of_island += 1
if i < m - 1:
if grid[i + 1][j] == 1:
grid[i + 1][j] = "0"
use_list.append([i + 1, j])
size_of_island += 1
if j > 0:
if grid[i][j - 1] == 1:
grid[i][j - 1] = "0"
use_list.append([i, j - 1])
size_of_island += 1
if j < n - 1:
if grid[i][j + 1] == 1:
grid[i][j + 1] = "0"
use_list.append([i, j + 1])
size_of_island += 1
return size_of_island, grid
if __name__ == '__main__':
s = Solution()
g0 = []
# g1 = [["0"]]
# g2 = [["1", "1", "0", "0", "0"],
# ["1", "1", "0", "0", "0"],
# ["0", "0", "1", "0", "0"],
# ["0", "0", "0", "1", "1"]]
# for g in [g0, g1, g2]:
# print(s.numIslands(g))
a = [[1, 1, 0, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 1, 1],
[0, 0, 0, 1, 1]]
print(s.maxAreaOfIsland(a))