题解
思路
代码
class Solution:
### 0201 DFS(72 ms,18.7 MB)
def numIslands(self, grid: List[List[str]]) -> int:
# dfs使用 or
def dfs(i, j):
if not 0 <= i < len(grid) or not 0 <= j < len(grid[0]) or grid[i][j] != '1':
return
grid[i][j] = '0' # 已经访问的值置为0
dfs(i-1, j)
dfs(i+1, j)
dfs(i, j-1)
dfs(i, j+1)
cnt = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
dfs(i, j)
cnt += 1
return cnt
### 0201 BFS(160 ms,18.7 MB)
def numIslands(self, grid: List[List[str]]) -> int:
# bfs使用 and
def bfs(i, j):
q = [(i, j)] # 这里列表中可以存放列表 or 元组
while q:
(i, j) = q.pop(0)
if 0 <= i < len(grid) and 0 <= j < len(grid[0]) and grid[i][j] == '1':
grid[i][j] = '0' # 已经访问的值置为0
q += [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]
cnt = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
bfs(i, j)
cnt += 1
return cnt
岛屿的最大面积
305. 岛屿数量 II
class Solution(object):
def numIslands2(self, m, n, positions):
x_l = [0, 1, 0, -1]
y_l = [1, 0, -1, 0]
fa = {}
def find(x):
if fa[x] != x:
fa[x] = find(fa[x])
return fa[x]
res = []
now = 0
for x, y in positions:
v = x * n + y
if v not in fa:
fa[v] = v
now += 1
for idx in range(4):
xx = x + x_l[idx]
yy = y + y_l[idx]
if xx >= 0 and xx < m and yy >= 0 and yy < n:
vv = xx * n + yy
if vv in fa:
fa_vv = find(vv)
if fa_vv != v: # 通过查询并查集来判断是否为同一个连通分量
fa[fa_vv] = v
now -= 1
res.append(now)
return res
class Solution:
def numIslands2(self, m: int, n: int, positions: List[List[int]]) -> List[int]:
ids = {}
ans = []
num_islands = 0
for i, j in positions:
num_islands -= self.union(ids, i, j)
ans.append(num_islands)
return ans
def find(self, ids, i, j):
t = (i, j)
while t in ids and ids[t] != t:
ids[t] = ids[ids[t]]
t = ids[t]
return t
def union(self, ids, i, j):
if (i, j) in ids:
return 0
t = (i, j)
ids[t] = t
disappeared = 0
if (i - 1, j) in ids:
ni, nj = self.find(ids, i - 1, j)
if (ni, nj) != t:
disappeared += 1
ids[(ni, nj)] = t
if (i + 1, j) in ids:
ni, nj = self.find(ids, i + 1, j)
if (ni, nj) != t:
disappeared += 1
ids[ni, nj] = t
if (i, j - 1) in ids:
ni, nj = self.find(ids, i, j - 1)
if (ni, nj) != t:
disappeared += 1
ids[(ni, nj)] = t
if (i, j + 1) in ids:
ni, nj = self.find(ids, i, j + 1)
if (ni, nj) != t:
disappeared += 1
ids[ni, nj] = t
return disappeared - 1