最短路径算法----Dijkatra
来源:互联网 发布:进销存软件重要性 编辑:程序博客网 时间:2024/06/05 22:59
题目描述:对于上图中某个点i,求其他所有点和它的最近距离
适用于:没有负数边的情况;有向图、无向图都可以使用该算法
数据结构:可以使用二维矩阵代表图、也可以使用数据结构描述graph
算法:
- 用到的数据集合:s(点k到点i最近的距离), u(不在s中的其他点到i的距离)
- 算法描述:
- 取u中距离最近的点j,加入s
- 对于和j相邻的点,更新u中的距离
def dijkstra(graph, start_node):# graph:n*n matrix# find min distance from start_nodes = {start_node:0} # the minimum distance between node i and vu = {} # the distance between node i and v# init u: O(Vertex)for node, weight in enumerate(graph[start_node]):if node == start_node:continueif weight > 0:u[node] = weightelse:u[node] = 0xFFFFFF # max distancewhile u:# 1. from u get min distance node# 2. update s# 3. update u using min distance node# O(Edge+Vertex^2) if using graph data structure# O(Vertex^2) is using matrixmin_dist_node = min(u, key=u.get)dist = u[min_dist_node]s[min_dist_node] = distdel u[min_dist_node]for node, weight in enumerate(graph[min_dist_node]):if node in u and weight > 0:u[node] = min(u[node], dist + weight)return s使用:
graph = [[0, 7, 9, 0, 0, 14], [7, 0, 10, 15, 0, 0], [9, 10, 0, 11, 0, 2], [0, 15, 11, 0, 6, 0], [0, 0, 0, 6, 0, 9], [14, 0, 2, 0, 9, 0] ]print dijkstra(graph, 0)
性能分析:
如果使用图的数据结构,每条边只遍历一次,根据min获取s中最小边的方式,有不同的答案:
1.如果使用堆结构维护u的话:更新O(log(Vertex)),找最小节点O(1)。遍历n个节点,需要O(Vertex*log(Vertex));更新边需要更新u,需要O(Edge*log(Vertex))。最终复杂度为O(Vertex*log(Vertex)+Edge*log(Vertex))2. 如果使用map维护u的话:更新O(1),找最小节点O(Vertex)。遍历n个节点,需要O(Vertex^2);更新边只要O(Edge)。最终复杂度为O(Vertex^2 + Edge)
如果使用邻接矩阵,O(Vetex^2)
附录:带上最短路径pre_node_map
def dijkstra(graph, start_node):# graph:n*n matrix# find min distance from start_nodepre_node_map = {start_node: -1}s = {start_node:0} # the minimum distance between node i and vu = {} # the distance between node i and v# init u: O(Vertex)for node, weight in enumerate(graph[start_node]):if node == start_node:continueif weight > 0:u[node] = weightpre_node_map[node] = start_nodeelse:u[node] = 0xFFFFFF # max distancewhile u:# 1. from u get min distance node# 2. update s# 3. update u using min distance node# O(Edge) if using graph data structure# O(Vertex^2) is using matrixmin_dist_node = min(u, key=u.get)dist = u[min_dist_node]s[min_dist_node] = distdel u[min_dist_node]for node, weight in enumerate(graph[min_dist_node]):if node in u and weight > 0:if dist + weight < u[node]:u[node] = dist + weightpre_node_map[node] = min_dist_nodeprint "pre_node_map", pre_node_mapreturn s
阅读全文
0 0
- 最短路径算法----Dijkatra
- Dijkatra 算法 计算一个点到其他点的最短路径
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- 最短路径算法
- Android 平台DES加密解密
- javabean,和map有什么区别? javabean完全可以用map替代
- Scala数据类型
- 《一》注册订阅号并完成基本配置
- iOS开发对象和指针
- 最短路径算法----Dijkatra
- 小米笔记本安装原生win7
- 互联网协议入门
- CSS样式display:inline的使用 与元素居中显示
- 微信公众号网页H5 微信支付
- LeetCode: 561. Array Partition I
- 极客学院tensorflow教程中缺失的inputdata.py代码
- 总结:java设计模式之---工厂方法
- metasploit基本用法