我有另一个程序输出的X和Y点,我想知道是否有一种方法可以使用Dijkstra的算法来规划连接所有点的最可能路径?
例如
----4------5
|
8------7-----6----[0]------1-------2-----3
|
9---
示例中的[0]
将是起点,数字将是导入文件中的点。假设这些要点是..
point X Y
1 2 0
2 4 0
3 6 0
0 0 0
4 2.5 2.5
5 4.5 2.5
6 -2 0
7 -4 0
8 -6 0
9 -4.5 -2.5
将这些点发送到Dijkstra的算法后,我希望输出路径类似于...
output= {
'0': ['1', '6'],
'1': ['2', '4'],
'2': ['3'],
'4': ['5'],
'6': ['7'],
'7': ['8','9']
}
如果您注意到点0
可能不在数据的开始,而是在中间。同样,输出包括所有点,没有任何一个被忽略。
当数字变大时,我正在工作的代码似乎会指出,这就是为什么我想使用Dijkstra的原因。任何帮助将不胜感激。
一些有效的代码
import math, collections
data = {0.0: [0.0, 0.0], 1.0: [1.0, 0.0], 2.0: [2.0, 0.0], 3.0: [3.0, 0.0], 4.0: [1.5, 0.5], 5.0: [2.5, 0.5], 6.0: [-1.0, 0.0], 7.0: [-2.0, 0.0], 8.0: [-3.0, 0.0], 9.0: [-2.5, -0.5]}
def group(d, start, seen = []):
x, y = d[start]
r = [a for a, [j, k] in d.items() if a != start and a not in seen and math.hypot(abs(x-j), abs(y-k)) <= 1]
if not r:
return {}
result = {start:r}
for i in r:
result.update(group(d, i, seen+[start, *r]))
return result
result = group(data, 0)
我找到了Dijkstra算法Here
的示例Dijkstra的算法
import sys
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex tDistance from Source")
for node in range(self.V):
print(node, "t", dist[node])
# A utility function to find the vertex with
# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minDistance(self, dist, sptSet):
# Initilaize minimum distance for next node
min = sys.maxsize
# Search not nearest vertex not in the
# shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index
# Funtion that implements Dijkstra's single source
# shortest path algorithm for a graph represented
# using adjacency matrix representation
def dijkstra(self, src):
dist = [sys.maxsize] * self.V
dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
# Pick the minimum distance vertex from
# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minDistance(dist, sptSet)
# Put the minimum distance vertex in the
# shotest path tree
sptSet[u] = True
# Update dist value of the adjacent vertices
# of the picked vertex only if the current
# distance is greater than new distance and
# the vertex in not in the shotest path tree
for v in range(self.V):
if self.graph[u][v] > 0 and sptSet[v] == False and \
dist[v] > dist[u] + self.graph[u][v]:
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
];
g.dijkstra(0);
# This code is contributed by Divyanshu Mehta