|
楼主 |
发表于 2019-10-20 14:20:16
|
显示全部楼层
- # 起点starpoint,终点src
- def dijkstra_st(graph, startpoint, src):
- length = len(graph)
- # type_ = type(graph)
- # if type_ == list:
- # nodes = [i for i in xrange(length)]
- # elif type_ == dict:
- # nodes = graph.keys()
- if isinstance(graph, list):
- nodes = [i for i in range(length)]
- elif isinstance(graph, dict):
- nodes = graph.keys()
- visited = [src]
- path = {src:{src:[]}}
- nodes.remove(src)
- distance_graph = {src:0}
- pre = next = src
- while nodes:
- distance = float('inf')
- for v in visited:
- for d in nodes:
- new_dist = graph[src][v] + graph[v][d]
- if new_dist <= distance:
- distance = new_dist
- next = d
- pre = v
- graph[src][d] = new_dist
- path[src][next] = [i for i in path[src][pre]]
- path[src][next].append(next)
- distance_graph[next] = distance
- visited.append(next)
- nodes.remove(next)
- # return distance_graph, path
- dist = distance_graph[startpoint]
- path1 = path[src][startpoint]
- path1.reverse()
- path1.append(src)
- return dist, path1
- if __name__ == '__main__':
- graph_list = [ [0, 1, 2, 999, 7, 4, 8, 999],
- [1, 0, 2, 5, 999, 999, 7, 999],
- [2, 2, 0, 1, 5, 999, 999, 999],
- [999, 5, 1, 0, 3, 999, 999, 6],
- [7, 999, 5, 3, 0, 3, 999, 4],
- [4, 999, 999, 999, 3, 0, 2, 6],
- [8, 7, 999, 999, 999, 2, 0, 4],
- [999, 999, 999, 6, 4, 6, 4, 0]]
- # 从1到8节点的最短路径
- distance, path = dijkstra_st(graph_list, 0, 7)
- print('\n', '最优路径为: ', path)
- print(' 最优路径对应的最短距离为: %d' % distance, '\n')
- # 从2到8节点的最短路径
- distance, path = dijkstra_st(graph_list, 1, 7)
- print('最优路径为: ', path)
- print('最优路径对应的最短距离为: %d' % distance, '\n')
- # 从3到7节点的最短路径
- distance, path = dijkstra_st(graph_list, 2, 6)
- print('最优路径为: ', path)
- print('最优路径对应的最短距离为: %d' % distance, '\n')
-
复制代码 输出为:
- 最优路径为: [0, 2, 3, 7]
- 最优路径对应的最短距离为: 9
- 最优路径为: [1, 2, 3, 7]
- 最优路径对应的最短距离为: 9
- 最优路径为: [2, 0, 5, 6]
复制代码
参考:【1】MATLAB dijkstra最短路算法
|
|