I found myself not as enthusiastic as before.
这里使用岛屿下沉的思路来进行计数。
原题目给出的是四周(上下左右,“十”字)都是水则为岛,升级为题为上下左右丿捺(“米”字)。给出解法,只需要按照鉴定岛屿的连通方式输入对应的参数即可:
def n_lands(grid, dx, dy):
# 利用下沉的思想判断到底有几个岛屿
n_ = 0
def sink(i,j):#当前下沉点的坐标
# 终止条件
if grid[i][j] == 0:
return 0
grid[i][j] = 0
for idx in range(len(dx)):
x = i + dx[idx]
y = j + dy[idx]
if len(grid) > x >= 0 and len(grid[i]) > y >=0:
if grid[x][y] == 0:
continue
sink(x,y)
return 1
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 0:
continue
n_ += sink(i,j)
return n_
结果:
if __name__ == '__main__':
#原问题求解
dx = [-1,1,0,0] # “十”字连通
dy = [0,0,-1,1]
print(n_lands([[1,0,0,1,0],
[0,0,1,0,1],
[1,0,0,1,1]], dx, dy)) # 5
“十”字方向 -- 手图
if __name__ == '__main__':
#升级问题求解
dx = [-1,1,0,0,1,1,-1,-1] # ”米”字连通
dy = [0,0,-1,1,-1,1,1,-1]
print(n_lands([[1,0,0,1,0],
[0,0,1,0,1],
[1,0,0,1,1]], dx, dy)) # 3
“米”字方向 -- 手图
网友评论