在Dijkstra上查找目标节点’;Python中带优先级队列的s算法
我有一个使用邻接列表的图的实现,我想让它与Dijkstra的算法一起工作。我不知道我是否已经脑死亡,但我想不出一种方法让优先级队列版本找到从源到开始的最短路径。我读过维基百科页面,但这还不够。有人能帮忙吗在Dijkstra上查找目标节点’;Python中带优先级队列的s算法,python,algorithm,Python,Algorithm,我有一个使用邻接列表的图的实现,我想让它与Dijkstra的算法一起工作。我不知道我是否已经脑死亡,但我想不出一种方法让优先级队列版本找到从源到开始的最短路径。我读过维基百科页面,但这还不够。有人能帮忙吗 class Vertex: def __init__(self,key): self.id = key self.connectedTo = {} def addNeighbor(self,nbr,weight=0): self.connectedTo[nbr] =
class Vertex:
def __init__(self,key):
self.id = key
self.connectedTo = {}
def addNeighbor(self,nbr,weight=0):
self.connectedTo[nbr] = weight
def __str__(self):
return str(self.id) + ' connectedTo: ' + str([x.id for x in self.connectedTo])
def getConnections(self):
return self.connectedTo.keys()
def getId(self):
return self.id
def getWeight(self,nbr):
return self.connectedTo[nbr]
class Graph:
def __init__(self):
self.vertList = {}
self.numVertices = 0
def addVertex(self,key):
self.numVertices = self.numVertices + 1
newVertex = Vertex(key)
self.vertList[key] = newVertex
return newVertex
def getVertex(self,n):
if n in self.vertList:
return self.vertList[n]
else:
return None
def __contains__(self,n):
return n in self.vertList
def addEdge(self,f,t,cost=0):
if f not in self.vertList:
nv = self.addVertex(f)
if t not in self.vertList:
nv = self.addVertex(t)
self.vertList[f].addNeighbor(self.vertList[t], cost)
def getVertices(self):
return self.vertList.keys()
def __iter__(self):
return iter(self.vertList.values())
def main(self, input1):
"""
Automates the insertion process
"""
try:
if input1 is None:
ans=True
while ans != False:
print ("""
1.Insert nodes
2.Print representation
3.Exit
""")
ans=input("What would you like to do?")
if ans=="1":
rfilename = input("Enter file to read: ")
f = open(rfilename) #file 1
linelist = list(f) #linelist is a list with each member corresponding to one line in the txt file
for i in range(len(linelist)): #inserts all vertexes
line = linelist[i].split()
self.addVertex(line[0])
for i in range(len(linelist)): #inserts all edges
line = linelist[i].split()
self.addEdge(line[0], line[1], int(line[2]))
elif ans=="2":
for v in self:
for w in v.getConnections():
print("( %s to %s, %s)" % (v.getId(), w.getId(), v.getWeight(w)))
elif ans=="3":
ans = False
except(FileNotFoundError):
print("File not found")
def dijkstra(self,start):
pq = PriorityQueue()
start.setDistance(0)
pq.insert([(v.getDistance(),v) for v in self])
while not pq.is_empty():
currentVert = pq.remove()
for nextVert in currentVert.getConnections():
newDist = currentVert.getDistance() + currentVert.getWeight(nextVert)
if newDist < nextVert.getDistance():
nextVert.setDistance( newDist )
nextVert.setPred(currentVert)
pq.decreaseKey(nextVert,newDist)
类顶点:
def uuu init uuuu(self,key):
self.id=key
self.connectedTo={}
def添加邻居(自身、nbr、重量=0):
自连接至[nbr]=重量
定义(自我):
返回str(self.id)+'connectedTo:'+str([self.connectedTo中x的x.id])
def getConnections(自):
返回self.connectedTo.keys()
def getId(自身):
返回self.id
def getWeight(自身,nbr):
返回自连接到[nbr]
类图:
定义初始化(自):
self.vertList={}
self.numVertices=0
def addVertex(自身,关键点):
self.numVertices=self.numVertices+1
newVertex=顶点(关键点)
self.vertList[键]=新顶点
返回新顶点
def getVertex(自身,n):
如果self.vertList中有n:
返回self.vertList[n]
其他:
一无所获
def___;包含___;(self,n):
在self.vertList中返回n
def附加值(自身、f、t、成本=0):
如果f不在self.vertList中:
nv=自添加顶点(f)
如果t不在self.vertList中:
nv=自添加顶点(t)
self.vertList[f].addNeighbor(self.vertList[t],成本)
def getVertices(自):
返回self.vertList.keys()
定义(自我):
返回iter(self.vertList.values())
def主(自身,输入1):
"""
自动执行插入过程
"""
尝试:
如果input1为无:
ans=真
而ans!=错误:
打印(“”)
1.插入节点
2.印刷代表
3.退出
""")
ans=输入(“您想做什么?”)
如果ans==“1”:
rfilename=input(“输入要读取的文件:”)
f=打开(rfilename)#文件1
linelist=list(f)#linelist是一个列表,其中每个成员对应于txt文件中的一行
对于范围内的i(len(linelist)):#插入所有顶点
line=linelist[i].split()
self.addVertex(第[0]行)
对于范围内的i(len(linelist)):#插入所有边
line=linelist[i].split()
self.addEdge(第[0]行、第[1]行、第[2]行)
elif ans==“2”:
对于自我中的v:
对于v.getConnections()中的w:
打印((%s到%s,%s)%)(v.getId(),w.getId(),v.getWeight(w)))
elif ans==“3”:
ans=错误
除了(FileNotFoundError):
打印(“未找到文件”)
def dijkstra(自启动):
pq=优先级队列()
开始。设置距离(0)
pq.insert([(v.getDistance(),v)表示self中的v])
而不是pq。是否为空()
currentVert=pq.remove()
对于currentVert.getConnections()中的nextVert:
newDist=currentVert.getDistance()+currentVert.getWeight(nextVert)
如果newDist
基于Python算法
带有“Magnus Lie Hetland”的书,您可以使用模块优雅地完成它。此模块提供堆队列算法(也称为优先级队列算法)的实现
from heapq import heappush, heappop
def dijkstra(G, s):
D, P, Q, S = {s:0}, {}, [(0,s)], set() #Est., tree, queue, visited
while Q: #Still unprocessed nodes?
_, u = heappop(Q) #Node with lowest estimate
if u in S: continue #Already visited? Skip it
S.add(u) #We've visited it now
for v in G[u]: #Go through all its neighbors
relax(G, u, v, D, P) #Relax the out-edge
heappush(Q, (D[v], v)) #Add to queue, w/est. as pri
return D, P #Final D and P returned
Dijkstra的算法可能类似于Prim的算法(队列有另一组优先级),但它是
也与另一个老的最爱密切相关:
BFS
我如何才能将此更改为包括在目标处停车?