求出最短路径,要过程,用Dijkstra算法。。。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了求出最短路径,要过程,用Dijkstra算法。。。相关的知识,希望对你有一定的参考价值。
参考技术A 从v1开始遍历v2 = 2;
v3 = 5;
v2较小所以跳到v2
v3 = 4;
v4 = 6;
v5 = 8;
v3较小所以跳到v3
v4 = 5;
v6 = 7;
v4较小所以跳到v4
v6 = 6;
v7 = 9;
v6较小所以跳到v6
v7 = 8;
所以最后结果v1 -> v7最短路径为v1->v2->v3->v4->v6->v7,最短路径长度为8 参考技术B
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#import collections
import heapq
#==============================================================================
# class Graph:
# def __init__(self):
# self.edges =
#
# def neighbors(self,id):
# return self.edges[id]
#==============================================================================
# 原型
class GraphWithWeights():
def __init__(self):
#super.__init__(self)
self.edges_weights =
def cost(self, from_node, to_node):
return self.edges_weights.get(from_node).get(to_node)
def neighbors(self,node):
return list(self.edges_weights.get(node).keys())
class PriorityQueue:
def __init__(self):
self.elements = []
# 检查优先序列是否为空
def empty(self):
return len(self.elements) == 0
# 依据优先权重添加一个成员
def put(self, item, priority):
heapq.heappush(self.elements, (priority, item))
# 取出成员
def get(self):
return heapq.heappop(self.elements)[1]
# 根据图设置值,顶点,边,权重,
target_graph = GraphWithWeights()
target_graph.edges_weights =
'V1':'V2':2, 'V3':5,
'V2':'V1':2, 'V3':2, 'V4':4, 'V5':6,
'V3':'V1':5, 'V2':2, 'V4':1, 'V6':3,
'V4':'V2':4, 'V3':1, 'V5':4, 'V6':1,'V7':4,
'V5':'V2':6, 'V4':4, 'V7':1,
'V6':'V3':3, 'V4':1, 'V7':2,
'V7':'V4':4, 'V5':1, 'V6':2
# dijkstra 算法
def dijkstra_search(graph, start, goal):
#pass
frontier = PriorityQueue()
frontier.put(start, 0)
came_from =
came_from[start] = None
cost_so_far =
cost_so_far[start] = 0
while not frontier.empty():
current = frontier.get()
if current == goal:
break
for next in graph.neighbors(current):
new_cost = cost_so_far[current] + graph.cost(current,next)
if next not in cost_so_far or new_cost < cost_so_far[next]:
cost_so_far[next]=new_cost
priority = new_cost
frontier.put(next, priority)
came_from[next] = current
return came_from, cost_so_far
def reconstruct_path(came_from, start, goal):
current = goal
path = [current]
while current != start:
current = came_from[current]
path.append(current)
path.reverse()
return path
c, f = dijkstra_search(target_graph, 'V1', 'V7')
path=reconstruct_path(c,'V1','V7')
print("最短路径为:".format(path))
#==============================================================================
# 最短路径为:['V1', 'V2', 'V3', 'V4', 'V6', 'V7']
#==============================================================================
最短路径算法之Dijkstra算法
参考:《大话数据结构》
这是一个按照路径长度递增的次序产生最短路径的算法。它并不是一次求出源点到目标点的最短路径,而是一步步求出它们之间顶点的最短路径,过程中都是基于已经求出的最短路径的基础上,求得更远顶点的最短路径,最终得到想要的结果。
#define MAXVEX 9 #define INFINITY typedef int PathMatrix[MAXVEX] typedef int ShortPathTable[MAXVEX] void ShortestPath_Dijkstra(MGraph G, int v0, PathMatrix *p, ShortPathTable *D) { int v,w,k,min; int final[MAXVEX]; //final[w]=1表示求得顶点v0到vw的最短路径 for(v=0;v<G.numVertexes;v++) { final[v] = 0; //全部顶点初始化为未知最短路径状态 (*D)[v] = G.matrix[v0][v]; //将与v0点有连线的顶点加上权值 (*p)[v] = 0; //初始化路径数组p为0 } (*D)[v0] = 0; //v0至v0路径为0 final[v0] = 1; //v0至v0不需要求路径 /*开始主循环,每次求得v0到某个v顶点的最短路径*/ for(v=1;v<G.numVertexes;v++) { min = INFINITY; for(w=0;w<G.numVertexes;w++) //寻找离v0最近的顶点 { if(!final[w] && (*D)[w] < min) { k = w; min = (*D)[w]; } } } final[k] = 1; //将目前找到的最近的顶点置为1 for(w=0;w<G.numVertexes;w++) { if(!final[w] && (min + G.matrix[k][w])<(*D)[w]) //如果警告v顶点的路径比现在这条路径的长度短的话 { (*D)[w] = min + G.matrix[k][w]; (*p)[w] = k; } } }
以上是关于求出最短路径,要过程,用Dijkstra算法。。。的主要内容,如果未能解决你的问题,请参考以下文章