图源点到各个点的最短路径(DIJ)
# -*- coding: cp936 -*- import copy MV = 0xFFFFFFFF Vertexs = {0:'v0',1:'v1',2:'v2',3:'v3',4:'v4',5:'v5'} Arcs = [[MV,MV,10,MV,30,100],[MV,MV,5,MV,MV,MV],[MV,MV,MV,50,MV,MV],\ [MV,MV,MV,MV,MV,10],[MV,MV,MV,20,MV,MV],[MV,MV,MV,MV,MV,MV]] #初始化源点到目标点的最短路径 def init_dist(srcVertex): return Arcs[srcVertex] #某个节点的最短路径 def findShortestPathToVertex(srcVertex, Vertex, dist, targetSet): temp = Arcs[srcVertex][Vertex] path = [srcVertex, Vertex] rslt = [] for i in targetSet.keys(): if MV != Arcs[i][Vertex] and i != srcVertex: if Arcs[i][Vertex] + dist[i] < temp: temp = Arcs[i][Vertex] + dist[i] path = copy.deepcopy(targetSet[i]) path.append(Vertex) rslt.append(temp) rslt.append(path) return rslt #从未获取最短路径的节点中找到一条最短路径的节点 def findShortestPath(srcVertex, dist, targetSet): minValue = MV Vertex = -1 for i in Vertexs.keys(): if i not in targetSet.keys(): path = findShortestPathToVertex(srcVertex, i, dist, targetSet) if path[0] < minValue: minValue = path[0] Vertex = i pathInfo = path[1] if -1 != Vertex: targetSet[Vertex] = pathInfo dist[Vertex] = minValue def shortPath_DIJ(srcVertex): dist = init_dist(srcVertex) #targetSet = [srcVertex] targetSet = {srcVertex:[srcVertex]} for i in range(len(Vertexs) - 1): findShortestPath(srcVertex, dist, targetSet) print targetSet print dist shortPath_DIJ(0)