题目描述:对于上图中某个点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_node
s = {start_node:0} # the minimum distance between node i and v
u = {} # the distance between node i and v
# init u: O(Vertex)
for node, weight in enumerate(graph[start_node]):
if node == start_node:
continue
if weight > 0:
u[node] = weight
else:
u[node] = 0xFFFFFF # max distance
while 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 matrix
min_dist_node = min(u, key=u.get)
dist = u[min_dist_node]
s[min_dist_node] = dist
del 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_node
pre_node_map = {start_node: -1}
s = {start_node:0} # the minimum distance between node i and v
u = {} # the distance between node i and v
# init u: O(Vertex)
for node, weight in enumerate(graph[start_node]):
if node == start_node:
continue
if weight > 0:
u[node] = weight
pre_node_map[node] = start_node
else:
u[node] = 0xFFFFFF # max distance
while 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 matrix
min_dist_node = min(u, key=u.get)
dist = u[min_dist_node]
s[min_dist_node] = dist
del 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 + weight
pre_node_map[node] = min_dist_node
print "pre_node_map", pre_node_map
return s
Dijkstra算法是一种解决图中两点间最短路径问题的算法,适用于没有负权边的情况,无论图是有向还是无向。该算法通过维护一个距离集合s,不断更新未加入集合的点到起点的最短距离,最终得到所有点到起点的最短路径。在实现上,可以使用二维矩阵或特定数据结构表示图。
17万+

被折叠的 条评论
为什么被折叠?



