题目描述
策略是把两座岛屿的边缘都找出来,然后一一比对距离,最后输出,但是很明显这样子计算量很大
是可以跑出来的,就是会超时
class Solution:
def shortestBridge(self, grid: List[List[int]]) -> int:
island1_edge = collections.deque()
island2_edge = collections.deque()
directions=[(-1,0),(1,0),(0,-1),(0,+1)]
m = len(grid)
n = len(grid[0])
for i in range(m):
for j in range(n):
if grid[i][j]==1:
island1 = collections.deque([(i,j)])
break
while island1:
edge_flag = 0
x,y = island1.popleft()
grid[x][y]=0
for dx,dy in directions:
nx = x+dx
ny = y+dy
if 0<=nx<m and 0<=ny<n:
if grid[nx][ny]==1:
if (nx,ny) not in island1:
island1.append((nx,ny))
edge_flag += 1
elif (nx,ny) in island1_edge:
edge_flag+=1
else:
edge_flag+=1
if edge_flag != 4:
island1_edge.append((x,y))
for i in range(m):
for j in range(n):
if grid[i][j]==1:
island2 = collections.deque([(i,j)])
break
while island2:
edge_flag = 0
x,y = island2.popleft()
grid[x][y]=0
for dx,dy in directions:
nx = x+dx
ny = y+dy
if 0 <= nx < m and 0 <= ny < n:
if grid[nx][ny] == 1:
if (nx,ny) not in island2:
island2.append((nx, ny))
edge_flag += 1
elif (nx, ny) in island2_edge:
edge_flag += 1
else:
edge_flag += 1
if edge_flag != 4:
island2_edge.append((x, y))
shorestLength = 10000
for (x1,y1) in island1_edge:
for (x2,y2) in island2_edge:
shorestLength = min(shorestLength,abs(x1-x2)+abs(y1-y2))
return shorestLength-1
考虑第2种策略,就是以岛屿一为出发点,开始进行大水漫灌,成功AC
import collections
class Solution:
def shortestBridge(self, grid):
island1=collections.deque()
directions=[(-1,0),(1,0),(0,-1),(0,+1)]
m = len(grid)
n = len(grid[0])
exit = 0
for i in range(m):
for j in range(n):
if grid[i][j]==1:
to_check = collections.deque([(i,j)])
grid[i][j] = 2
exit = 1
break
if exit:
break
while to_check:
(x,y) = to_check.popleft()
island1.append((x,y))
for (dx,dy) in directions:
nx = x+dx
ny = y+dy
if 0<=nx<n and 0<=ny<m and grid[nx][ny]==1 and (nx,ny)not in to_check:
to_check.append((nx,ny))
grid[nx][ny]=2
shortesLength = -1
success = 0
while not success:
shortesLength += 1
while island1 and not success:
(x,y) = island1.popleft()
for (dx, dy) in directions:
nx = x + dx
ny = y + dy
if 0<=nx<n and 0<=ny<m:
if grid[nx][ny] == 1:
success = 1
break
elif grid[nx][ny] == 0:
grid[nx][ny] = 2
to_check.append((nx,ny))
island1=to_check
to_check = collections.deque()
return shortesLength
grid = [[0,1],[1,0]]
print(Solution().shortestBridge(grid))