python写的BFS一直TLE,还能咋优化
查看原帖
python写的BFS一直TLE,还能咋优化
628578
192210304230wgd楼主2022/1/24 13:28
import queue
q =queue.Queue()
n=int(input())
xy=[list(map(int,input().split())) for i in range (n)]
nex = [1,-1]#2个方向

def bfs(x):
    q.put((xy[x][0],0))
    vis[xy[x][0]]=1
    while q.empty()==False:
        now=q.get()
        y=xy[x][1]
        if now[0]==y:
            print(now[1])
            break
        if now[0]>y:
            new = now[0] + nex[1]
            newstep = now[1] + 1 
            if new>=0 and new<=2*y and vis[new]==0:
                vis[new]=1
                q.put((new,newstep))
        else:
            for i in range(3):
                if i==2:
                    new=2*now[0]
                else:
                    new=now[0]+nex[i]
                newstep =now[1]+1
                if new>=0 and new<=2*y and vis[new]==0:
                    vis[new]=1
                    q.put((new,newstep))

for i in range(n):
    vis = [0] * 200000
    bfs(i)
    q.queue.clear()
2022/1/24 13:28
加载中...