我的代码遇到问题,我无法计算起始节点到节点的距离。我有一个表格的文本文件:
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,7,8,9
这表示图中的节点距离。不幸的是,这是我的代码,尽管尝试了一些不同的方法,我仍然会不断提出各种错误消息。
infinity = 1000000
invalid_node = -1
startNode = 0
class Node:
distFromSource = infinity
previous = invalid_node
visited = False
def populateNodeTable():
nodeTable = []
index =0
f = open('route.txt', 'r')
for line in f:
node = map(int, line.split(','))
nodeTable.append(Node())
print nodeTable[index].previous
print nodeTable[index].distFromSource
index +=1
nodeTable[startNode].distFromSource = 0
return nodeTable
def tentativeDistance(currentNode, nodeTable):
nearestNeighbour = []
for currentNode in nodeTable:
# if Node[currentNode].distFromSource + currentDistance = startNode + currentNode
# currentDistance = currentNode.distFromSource + nodeTable.currentNode
currentNode.previous = currentNode
currentNode.length = currentDistance
currentNode.visited = True
currentNode +=1
nearestNeighbour.append(currentNode)
print nearestNeighbour
return nearestNeighbour
def shortestPath (nearestNeighbour)
shortestPath = []
f = open ('spf.txt', 'r')
f.close()
currentNode = startNode
if __name__ == "__main__":
populateNodeTable()
tentativeDistance(currentNode,populateNodeTable())
以'#'开头的行在我的tentativeDistance函数是给我带来麻烦的部分。我已经看过网络上的其他一些实现,虽然他们让我感到困惑
答案 0 :(得分:0)
def dijkstra(u,graph):
n = graph.numNodes
l = { u : 0 } ; W = graph.V()
F = [] ; k = {}
for i in range(0,n):
lv,v = min([ (l[lk],lk) for lk in l.keys() if lk in W ])
W.remove(v)
if v!=u: F.append(k[v])
for v1 in [ v2 for v2 in graph.G(v) if v2 in W ]:
if v1 not in l or l[v]+graph.w(v,v1) < l[v1]:
l[v1] = l[v] + graph.w(v,v1)
k[v1] = (v,v1)
return l,F
你需要一个带有方法V()的类图(产生图形节点),w(v1,v2)(产生边缘的权重(v1,v2)),删除(从中删除边缘)图)和属性numNodes(产生图中的节点数)和G(v)产生节点v的邻域。