python代码,求助大佬!测试点2、5错了
查看原帖
python代码,求助大佬!测试点2、5错了
1231862
lzysxfcs楼主2024/12/19 23:44
from collections import deque
def bfs(n,m,x,y):
    visited = [[False]*m for _ in range(n)]
    visited[x][y] = True
    directions = [(1,2),(1,-2),(2,1),(2,-1),(-1,2),(-1,-2),(-2,1),(-2,-1),(2,2),(2,-2),(-2,2),(-2,-2)]
    queue = deque([(x,y,0)])
    while queue:
        x,y,step = queue.popleft()
        if x == 0 and y == 0:
            return step
        for dx,dy in directions:
            nx,ny = x+dx,y+dy
            if 0 <= nx < n and 0 <= ny <m and not visited[nx][ny]:
                visited[nx][ny] = True
                queue.append((nx,ny,step+1))

x1,y1 = map(int,input().split())
x2,y2 = map(int,input().split())
n = max(x1,x2)
m = max(y1,y2)
x1,y1 = x1-1,y1-1
x2,y2 = x2-1,y2-1
print(bfs(n,m,x1,y1))
print(bfs(n,m,x2,y2))

2024/12/19 23:44
加载中...