练习 Dijkstra 最短路径算法。

#coding: utf-8

# Author: woodfox, Oct 14, 2014
# http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm """
Let the node at which we are starting be called the initial node. Let the distance of node Y be the distance from the initial node to Y. Dijkstra's algorithm will assign some initial distance values and will try to improve them step by step. 1. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. 2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes called the unvisited set consisting of all the nodes. 3. For the current node, consider all of its unvisited neighbors and calculate their tentative distances. Compare the newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B (through A) will be 6 + 2 = 8. If B was previously marked with a distance greater than 8 then change it to 8. Otherwise, keep the current value. 4. When we are done considering all of the neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again. 5. If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished. 6. Select the unvisited node that is marked with the smallest tentative distance, and set it as the new "current node" then go back to step 3.
""" vertices = [1, 2, 3, 4, 5, 6] # element structure is: [node1, node2, cost]
edges = [[1, 6, 14], [1, 2, 7], [1, 3, 9], [3, 6, 2], [2, 3, 10], [3, 4, 11], [2, 4, 15], [6, 5, 9], [5, 4, 6]] def get_neighbors(node):
# key is neighbor's node number, value is cost
result = {}
for edge in edges:
if edge[0] == node:
other = edge[1]
elif edge[1] == node:
other = edge[0]
else:
continue result[other] = edge[2] # cost
return result #print(get_neighbors(3))
#print(get_neighbors(5)) MAX_VALUE = 10000 def shorted_path(start, end):
unvisited = []
visited = []
costs = {}
#result_path = [] for v in vertices:
if v == start:
costs[v] = 0
else:
costs[v] = MAX_VALUE
unvisited.append(v) #print unvisited
#print costs current = start
#result_path.append(current) while True:
neighbors = get_neighbors(current)
min_cost_of_neighbor = MAX_VALUE
min_cost_n = None if len(neighbors.keys()) > 0:
for n, cost in neighbors.iteritems():
if n in visited:
continue
new_cost = costs[current] + cost
if new_cost < costs[n]:
costs[n] = new_cost
if costs[n] < min_cost_of_neighbor:
min_cost_of_neighbor = costs[n]
min_cost_n = n visited.append(current)
#print visited, unvisited, current, min_cost_n
unvisited.remove(current) if min_cost_n != None:
current = min_cost_n if end in visited:
break #print costs
return costs[end] print shorted_path(1, 5)

测试:

Running “dijkstra_test.py”…
Python 2.7.8teaser
Theme:
20
copy output
Program exited with code #0 after 0.05 seconds.

练习 Dijkstra 最短路径算法。的更多相关文章

  1. Java邻接表表示加权有向图,附dijkstra最短路径算法

    从A到B,有多条路线,要找出最短路线,应该用哪种数据结构来存储这些数据. 这不是显然的考查图论的相关知识了么, 1.图的两种表示方式: 邻接矩阵:二维数组搞定. 邻接表:Map<Vertext, ...

  2. 数据结构(c++)(第二版) Dijkstra最短路径算法 教学示范代码出现重大问题!

    前言 去年在数据结构(c++)的Dijkstra教学算法案例中,发现了一个 bug 导致算法不能正常的运行,出错代码只是4行的for循环迭代代码. 看到那里就觉得有问题,但书中只给了关键代码的部分,其 ...

  3. Dijkstra最短路径算法[贪心]

    Dijkstra算法的标记和结构与prim算法的用法十分相似.它们两者都会从余下顶点的优先队列中选择下一个顶点来构造一颗扩展树.但千万不要把它们混淆了.它们解决的是不同的问题,因此,所操作的优先级也是 ...

  4. 一篇文章讲透Dijkstra最短路径算法

    Dijkstra是典型最短路径算法,计算一个起始节点到路径中其他所有节点的最短路径的算法和思想.在一些专业课程中如数据结构,图论,运筹学等都有介绍.其思想是一种基础的求最短路径的算法,通过基础思想的变 ...

  5. Python 图_系列之纵横对比 Bellman-Ford 和 Dijkstra 最短路径算法

    1. 前言 因无向.无加权图的任意顶点之间的最短路径由顶点之间的边数决定,可以直接使用原始定义的广度优先搜索算法查找. 但是,无论是有向.还是无向,只要是加权图,最短路径长度的定义是:起点到终点之间所 ...

  6. Dijkstra最短路径算法实例

    #include <stdio.h>#include <stdlib.h>/* Dijkstra算法 */#define VNUM 5#define MV 65536int P ...

  7. 关于Dijkstra最短路径算法

    Dijkstra算法,不是很明白,今天找了一些博客看了一下,决定自己也写一个为以后忘记的时候可以看做准备. 实际上,如果理解没错的话,该算法实际上和枚举法有点像,只不过,在选取出发路径的路径都是最短路 ...

  8. SRM 583 Div II Level Three:GameOnABoard,Dijkstra最短路径算法

    题目来源:http://community.topcoder.com/stat?c=problem_statement&pm=12556 用Dijkstra实现,之前用Floyd算法写了一个, ...

  9. Dijkstra 最短路径算法 秒懂详解

    想必大家一定会Floyd了吧,Floyd只要暴力的三个for就可以出来,代码好背,也好理解,但缺点就是时间复杂度高是O(n³). 于是今天就给大家带来一种时间复杂度是O(n²),的算法:Dijkstr ...

随机推荐

  1. Java连接Oracle数据库示例

    1.数据库复用模块 package cn.jzy.database; import java.sql.Connection; import java.sql.DriverManager; import ...

  2. strcpy sprintf memcpy 它们之间的区别

    strcpy,sprintf,memcpy的区别 strcpy 函数操作的对象是 字符串,完成 从 源字符串 到 目的字符串 的 拷贝 功能.  snprintf 函数操作的对象 不限于字符串:虽然目 ...

  3. 简单分页查询(web基础学习笔记十三)

    一.建立资源文件和工具类 1.1 .database.properties jdbc.driver_class=oracle.jdbc.driver.OracleDriver jdbc.connect ...

  4. 每日一句英语:怎样回答美国人的How is it going问候语?

    和中国人"吃了吗"是一个性质,本质上仅仅是个话题的起始点,而不是真的想知道你吃了没有. 美国人打招呼有几种方式: 不太熟的人:How are you? 一 般说 pretty go ...

  5. $nextTick 宏任务 微任务 macrotasks microtasks

    1.nextTick调用方法 首先看nextTick的调用方法: https://cn.vuejs.org/v2/api/#Vue-nextTick // 修改数据 vm.msg = 'Hello' ...

  6. 像烟瘾一样的Adobe Flash,真的戒不掉吗?

    近来对Adobe Flash来说真是段难过的日子.Hacking Team公司外泄的440GB电子邮件数据已成为黑客挖掘安全漏洞的宝藏. 光是Flash就被发现了三个不同的漏洞: l  CVE-201 ...

  7. 如何提高SELECT的效率

      首先避免使用in ,not in,<>,<,<=,>,>=,is null,is not null 主要搜索字段建立索引 .WHERE子句中的连接顺序 sql解 ...

  8. java中相同名字不同返回类型的方法

    这种名字相同返回类型不同的方法,在同一个类中是无法共存的,不论是继承过来的方法,还是多实现过来的方法,在一个类内都无法共存.名字确定了,你能改的只有参数(重载).

  9. Linux密钥认证错误解决

    问题描述: Xshell用key认证登录,提示所选的用户密钥未在远程主机上注册 问题解决: 查看日志/var/log/secure,基本上都是用户根目录的权限问题 根据日志提示: Authentica ...

  10. SDK Build Tools revision (19.0.3) is too low for project Minimum required is 19.1.0

    假设你正在使用Android Studio工具进行开发,且将版本号更新到0.6.0的时候.莫名的出现这种错误 SDK Build Tools revision (19.0.3) is too low ...