目录
一、题目
给你一个大小为 m x n 的二进制矩阵 grid 。
岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在 水平或者竖直的四个方向上 相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。
岛屿的面积是岛上值为 1 的单元格的数目。
计算并返回 grid 中最大的岛屿面积。如果没有岛屿,则返回面积为 0 。
m == grid.length
n == grid[i].length
1 <= m, n <= 50
grid[i][j]
为0
或1
二、代码解析
1、BFS解法
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
row = len(grid)
cow = len(grid[0])
queue = []
realmax = 0
res = 0
for i in range(row):
for j in range(cow): #两个for循环将所有的格子都遍历一遍
if grid[i][j] == 1: #找到为1的格子就广度优先遍历找到相联的1
queue.append((i,j)) #加入到列表中
grid[i][j] = 0 #进入了就说明他走过,应该改为0避免死循环
res = 1 #进入了也得从1开始对这一整块的1计数
while len(queue) > 0: #BFS
nr,nc = queue.pop() #把队首pop出去,再找队首的下一级
for x,y in [(nr,nc-1),(nr,nc+1),(nr-1,nc),(nr+1,nc)]: #根据上下左右查找是否为1
if 0<= x < row and 0 <= y< cow and grid[x][y] == 1: #注意限制边界
queue.append((x,y)) #把所有队首下一级的元组都加入
grid[x][y] = 0 #走过的路设置为0
res += 1 #找到一个加一个
realmax = max(realmax,res) #通过寻找最大值来判断对最面积
return realmax
2、DFS解法
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
row = len(grid)
cow = len(grid[0])
stack = []
res = 0
realmax = 0
for p in range(row):
for q in range(cow):
if grid[p][q] == 1:
res = 1
stack.append((p,q))
grid[p][q] = 0
while len(stack) > 0:
nr,nc = stack.pop(-1)
for x,y in [(nr-1,nc),(nr+1,nc),(nr,nc+1),(nr,nc-1)]:
if 0 <= x < row and 0 <= y < cow and grid[x][y] == 1:
res += 1
stack.append((x,y))
grid[x][y] = 0
nr = x
nc = y
realmax = max(res,realmax)
return realmax
三、解题思路(典型岛屿问题)
1、容易疏漏的点
1.1BFS
- 找到第一个1就要加入到queue中,且把这个走过的地方设为0,且开始计数
- 在while循环中,找到相邻的1也要加入到queue中,且走过的地方设为0,计数
- res 和 realmax要提前先赋值
1.2 DFS
- 找到第一个1就要加入到stack中,且把这个走过的地方设为0,且开始计数
- 在while循环中,找到相邻的1也要加入到stack中,且走过的地方设为0,计数
- res 和 realmax要提前先赋值
- for循环附近的1中坚持一条路走到黑,利用当前的x和y去使得下一步去找(x,y)相邻格子,一直改变nr,nc的值直到所有格子被走完
2、尝试了一下并查集
并查集更时候查有多少个小岛(全面的概况出现小岛数量)
BFS、DFS更适合找小岛里面的最大面积(精细到局部上)