我正在编写一个基于BFS的代码,其中必须计算与标记为1的框的最近距离。标记为1的框的距离为0。
这是Google kickstart 2019回合A:包裹中的问题。
链接:https://codingcompetitions.withgoogle.com/kickstart/round/0000000000050e01/000000000006987d
import time
def multibfs (office, r, c):
#office is a 2-D list with 0's and 1's
visited = [[False]*c for x in range (r)]
values = [[1e9]*c for x in range (r)] #closest distance
queue = [] #Bfs queue
for i in range (r):
for j in range (c):
if office[i][j]==1:
visited[i][j]=True
values[i][j]=0
queue.append([i,j])
while queue:
s = queue.pop(0)
iPos = s[0]
jPos = s[1]
for i in range (iPos-1, iPos+2):
if i in range (0, r):
if visited[i][jPos] == False:
queue.append([i, jPos])
visited[i][jPos] = True
values[i][jPos] = values[iPos][jPos] + 1
for j in range (jPos-1, jPos+2):
if j in range (0, c):
if visited[iPos][j] == False:
queue.append([iPos, j])
visited[iPos][j] = True
values[iPos][j] = values[iPos][jPos] + 1
return values
tic=time.time()
o = [[1]*250 for x in range (250)]
val = multibfs(o, 250, 250)
print(time.time()-tic)
对于r和c等于250,并且office只有1的情况,python3.6的执行时间大约为0.7s。 我希望PyPy的实现会更快,但是会花费更长的时间