import time
class DJ:
def __init__(self, roads, n):
self.roads, self.n=roads,n
#Dijkstra with mod for a pathway from vertex a to c
#returns dist of a to all points if arg c is 0
def dis(self,a,c):
spset,dist,prev,path,k=[],['d'],['d'],[],[]
dist.extend([float("inf")]*self.n)
prev.extend([0]*self.n)
dist[a]=0
if a==c:
return [a]
while len(spset)!=self.n:
k=[dist[m] for m in range(1,self.n+1) if m not in spset]
for i in range(1,self.n+1):
if dist[i]==min(k) and i not in spset:
s=i
spset.append(s)
break
for i in range(1, self.n+1):
if self.roads[s][i]==1 and dist[s]+1<dist[i]:
dist[i]=dist[s]+1
prev[i]=s
if i==c:
path.append(c)
while c!=a:
path.append(prev[c])
c=prev[c]
return path
k=[]
return dist
乍一看,有什么办法可以优化这个功能吗?我在python中并不是很有经验。刚开始一周前。我只需要这个速度快0.1到0.2秒。它基于spt algo Dijkstra。我很抱歉这么少描述。
例如: 如果顶点(边)是:
(1,2)
(2,3)
(3,4)
(4,5)
dis(1,3)
应该将路径从1返回到3,即[1,2,3]
,否则如果c为0,即dis(2,0)
应该从所有点返回2的距离,即[1,0,1,2,3]