[英]How to find the shortest path between two coordinates in a 2-dimensional array?
我試圖找到從二維數組中的一個點(一個坐標,x 和 y 值代表它在數組中的 position)到另一個點的最短方法。
我想 output 一個坐標數組,必須經過這些坐標才能從初始坐標到最終坐標。
像這樣的數組的一個例子可能是
arr = [
[15, 7, 3],
[1, 2, 6],
[7, 4, 67]
]
在這種情況下,我們可以說我們將從arr[0][0]
開始並在arr[2][2]
結束。 因此,坐標將是(0, 0)
和(2, 2)
。
預期的 output 將是: [(0, 2), (1, 2), (2, 2), (2, 1)]
或相同長度的東西。
我試過的
我設法在下面制作了一個半成功的 function,但在較大的情況下效率非常低且耗時。
import math
arr = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
coor1 = (0, 0) # seen as 2 in the arr array
coor2 = (2, 2) # seen as 7 in the arr array
def pythagoras(a, b):
# find pythagorean distances between the two
distance_y = max(a[0], b[0]) - min(a[0], b[0])
distance_x = max(a[1], b[1]) - min(a[1], b[1])
# calculate pythagorean distance to 3 d.p.
pythag_distance = round(math.sqrt(distance_x**2 + distance_y**2), 3)
return pythag_distance
def find_shortest_path(arr, position, target):
''' finds shortest path between two coordinates, can't go diagonally '''
coordinates_for_distances = []
distances = []
for i in range(len(arr)):
for r in range(len(arr)):
coordinates_for_distances.append((i, r))
distances.append(pythagoras((i, r), target))
route = []
while position != target:
acceptable_y_range = [position[1] + 1, position[1] - 1]
acceptable_x_range = [position[0] + 1, position[0] - 1]
possibilities = []
distance_possibilities = []
for i in range(len(coordinates_for_distances)):
if coordinates_for_distances[i][0] == position[0] and coordinates_for_distances[i][1] in acceptable_y_range:
possibilities.append(coordinates_for_distances[i])
distance_possibilities.append(distances[i])
elif coordinates_for_distances[i][1] == position[1] and coordinates_for_distances[i][0] in acceptable_x_range:
possibilities.append(coordinates_for_distances[i])
distance_possibilities.append(distances[i])
zipped_lists = zip(distance_possibilities, possibilities)
minimum = min(zipped_lists)
position = minimum[1]
route.append(position)
return route
為了找到一對坐標之間的最短路徑,我們可以將其轉化為一個圖問題,其中每個坐標都是一個圖節點。 現在在這種設置下,找到兩個節點之間的最短路徑是一個眾所周知的圖論問題,並且使用正確的工具很容易解決。
我們可以使用NetworkX ,它實際上有一個Graph generator ,它返回mxn
個節點的 2d 網格圖,每個節點都連接到它最近的鄰居。 這是完美的案例:
import networkx as nx
from matplotlib import pyplot as plt
G = nx.grid_2d_graph(3,3)
plt.figure(figsize=(6,6))
pos = {(x,y):(y,-x) for x,y in G.nodes()}
nx.draw(G, pos=pos,
node_color='lightgreen',
with_labels=True,
node_size=600)
現在我們可以使用 networkX 的nx.bidirectional_shortest_path
來找到兩個坐標之間的最短路徑:
coor1 = (0, 2) # seen as 2 in the arr array
coor2 = (2, 1) # seen as 7 in the arr array
nx.bidirectional_shortest_path(G, source=coor1, target=coor2)
# [(0, 2), (1, 2), (2, 2), (2, 1)]
請注意, nx.grid_2d_graph
將生成最多具有任意大m
和n
的網格圖,通過定位標簽,您還可以 plot 坐標網格,就像上面一樣:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.