本博客在学习北京大学陈斌老师《数据结构与算法》MOOC课程中总结反思形成。
准备阶段
实现阶段
可视化
陈斌老师实现的最短路算法
def dijkstra(aGraph, start):
pq = PriorityQueue()
start.setDistance(0)
# 对所有顶点建堆,形成优先队列
pq.buildHeap([(v.getDistance(), v) for v in aGraph])
while not pq.isEmpty():
# 优先队列出队
currentVert = pq.delMin()
for nextVert in currentVert.getConnections():
newDist = currentVert.getDistance() + currentVert.getWeight(nextVert)
if newDist < nextVert.getDistance():
# 修改出队顶点所邻接顶点的distm并逐个重拍队列
nextVert.setDistance(newDist)
nextVert.setPred(currentVert)
pq.decreaseKey(nextVert, newDist)
自己为调用该算法实现的图的创建和路径回溯
这里为了方便以后的调用,考虑到邻接矩阵使用的广泛性,实现了给定邻接矩阵,创建邻接表图
# 实现邻接矩阵转化为邻接图
def Matrix2Graph(LJGraph, LJmatrix):
for i in range(len(LJmatrix)):
LJGraph.addVertex(i)
for i in range(len(LJmatrix)):
for j in range(len(LJmatrix[0])):
if i != j:
LJGraph.addEdge(i, j, LJmatrix[i][j])
# 检验构造的图的正确性
for v in LJGraph:
for w in v.getConnections():
print("%s,%s" % (v.getId(), w.getId()))
print(v.getWeight(w))
在Dijkstra算法求解出最短路后,回溯出终点到起点的最短路径
def traverse(y):
x = y
_temp = []
_temp.append(x.getId())
while (x.getPred()):
_temp.append(x.getPred().getId())
x = x.getPred()
return _temp
if __name__ == '__main__':
LJGraph = Graph()
LJmatrix = [[0, 2, 5, 1, sys.maxsize, sys.maxsize],
[2, 0, 3, 2, sys.maxsize, sys.maxsize],
[5, 3, 0, 3, 1, 5],
[1, 2, 3, 0, 1, sys.maxsize],
[sys.maxsize, sys.maxsize, 1, 1, 0, 1],
[sys.maxsize, sys.maxsize, 5, sys.maxsize, 1, 0]]
# 复习:对于基础的二维列表,利用len获取形状
# print(LJmatrix)
# print(LJmatrix[0][1])
Matrix2Graph(LJGraph, LJmatrix)
# 如何使用Dijkstra(迪杰斯特拉算法)算法
dijkstra(LJGraph, LJGraph.getVertex(0))
# 如何反向调用得到图的解
path = traverse(LJGraph.getVertex(5))
print(path)
dijkstra(LJGraph, LJGraph.getVertex(0))
# 如何反向调用得到图的解
path = traverse(LJGraph.getVertex(5))
print(path)