305. Number of Islands II
矩阵dfs类型题
题干:
A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
解释:
给一个二维平面,要求返回每次添加一个小岛之后总的小岛数量如何变化
思考:
小岛类型的题一般都是用的并查集的思路来做,首先,添加一个小岛,无非有3种情况: 1,小岛周围没有别的小岛,全是0 2,小岛周围有别的小岛 2.1 周围的小岛全是一个颜色的 2.2 周围的小岛不是一个颜色的
对于情况1,小岛数等于之前的数字+1,把新的小岛染上一个新的颜色即可。 对于情况2.1,小岛数不变,把当前小岛加入到周围的颜色中 对于情况2.2 小岛数减一,把两种颜色合并为一种即可。 所以用一个hash来保存颜色对应的小岛的位置,然后对每个操作点进行更新和搜索即可。 但是这个思路有一个问题,如何确定周围的点的颜色呢?可以先把对应点直接修改为对应颜色存储,然后在要修改颜色的时候通过hash拿到本颜色对应的所有点然后全部修改。
答案:
from typing import List
from collections import defaultdict
class Solution:
def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]:
grid = [[0]*n for _ in range(m)]
island = defaultdict(set)
directions =[[1,0],[-1,0],[0,-1],[0,1]]
index =1
res =[]
for x,y in positions:
if grid[x][y]:
res.append(len(island))
continue
mark = []
for dx,dy in directions:
if 0<=x+dx<m and 0<=y+dy<n and grid[x+dx][y+dy] and grid[x+dx][y+dy] not in mark:
mark.append(grid[x+dx][y+dy])
if len(mark) ==0:
grid[x][y] =index
island[index].add((x,y))
index+=1
else:
temp = mark[0]
grid[x][y] =temp
island[temp].add((x,y))
for num in mark[1:]:
for i,j in island[num]:
grid[i][j]=temp
island[temp] |=island[num]
del island[num]
res.append(len(island))
return res