Day 29
Date: October 25, 2022 1:09 PM
LinkedIn: https://leetcode.cn/problems/shortest-bridge/description/
Title: 最短的桥
深搜+广搜,这道题个人感觉挺难的,看了好久题解。
它其实就是用深搜找到第一个岛所有的坐标,然后进行广搜,一层一层的找能否跟第二个岛屿接上。其中用2 和 1 来区分第一个第二个岛屿。
class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
def dfs(i,j):
q.append((i,j)) # 第一个岛屿中的坐标入队
grid[i][j] = 2 # 第一个岛的区域赋值为2
for a, b in pairwise(dirs):# 对dirs中元素成对取值 上右下左
x, y = i + a, j + b # 上就是行-1 下就是行+1 左就是列-1 右就是列+1
if 0 <= x < n and 0 <= y < n and grid[x][y] == 1:# 如果上下左右对应的坐标中还是第一个岛屿
dfs(x, y)
n = len(grid)
dirs = (-1, 0, 1, 0, -1) # 上-1,0 下1,0 左0,-1 右0,1
q = deque()
i, j = next((i,j) for i in range(n) for j in range(n) if grid[i][j]) # 取第一个grid[i][j]不为0的下标
dfs(i,j) # 开始深搜
ans = 0
while 1:# bfs
for _ in range(len(q)): # 未拓展前的队列q遍历
i, j = q.popleft()# 最近入队的出队
for a, b in pairwise(dirs):
x, y = i+a, j+b
if 0 <= x < n and 0 <= y < n:
if grid[x][y] == 1:
return ans # 遇到第二个岛屿
if grid[x][y] == 0:
grid[x][y] = 2 # 如果是边缘则变为2
q.append((x, y))
ans += 1 # 没有遇到第二个岛屿 ans+1
next()用法:
-
next(iterator[,default])
-
iterator :要读取行的文件对象
default :如果迭代器耗尽则返回此默认值。 如果没有给出此默认值,则抛出 StopIteration 异常
返回下一个输入行
-
如:
a = [1,3,6] next((i for i in a if i > 5),0) # output: 6
-
pairwise()用法:
-
itertools.pairwise()
- 从对象中获取连续的重叠对
- 如:
a = pairwise('12345') # 输出的a应为是 12 23 34 45