[英]Minimal cost path of 2d matrix
I am trying to find the minimal cost path from point (0, 0) to point {(u, v) |我试图找到从点 (0, 0) 到点 {(u, v) | 的最小成本路径u + v <= 100} in a 2d matrix of data I have generated.
u + v <= 100} 在我生成的二维数据矩阵中。
My algorithm is pretty simple and currently I have managed to produce the following (visualized) results, which leads me to understand that I am way off in my algorithm.我的算法非常简单,目前我已经设法产生以下(可视化)结果,这让我明白我的算法离我很远。
# each cell of path_arr contains a tuple of (i,j) of the next cell in path.
# data contains the "cost" of stepping on its cell
# total_cost_arr is used to assist reconstructing the path.
def min_path(data, m=100, n=100):
total_cost_arr = np.array([np.array([0 for x in range(0, m)]).astype(float) for x in range(0, n)])
path_arr = np.array([np.array([(0, 0) for x in range(0, m)], dtype='i,i') for x in range(0, n)])
total_cost_arr[0, 0] = data[0][0]
for i in range(0, m):
total_cost_arr[i, 0] = total_cost_arr[i - 1, 0] + data[i][0]
for j in range(0, n):
total_cost_arr[0, j] = total_cost_arr[0, j - 1] + data[0][j]
for i in range(1, m):
for j in range(1, n):
total_cost_arr[i, j] = min(total_cost_arr[i - 1, j - 1], total_cost_arr[i - 1, j], total_cost_arr[i, j - 1]) + data[i][j]
if total_cost_arr[i, j] == total_cost_arr[i - 1, j - 1] + data[i][j]:
path_arr[i - 1, j - 1] = (i, j)
elif total_cost_arr[i, j] == total_cost_arr[i - 1, j] + data[i][j]:
path_arr[i - 1, j] = (i, j)
else:
path_arr[i, j - 1] = (i, j)
each cell of path_arr contains a tuple of (i,j) of the next cell in path. path_arr 的每个单元格都包含路径中下一个单元格的 (i,j) 元组。 data contains the "cost" of stepping on its cell, and total_cost_arr is used to assist reconstructing the path.
data 包含踩踏其单元格的“成本”,total_cost_arr 用于协助重建路径。
I think that placing (i,j) in previous cell is causing some conflicts which lead to this behavior.我认为将 (i,j) 放在前一个单元格中会引起一些冲突,从而导致这种行为。
I don't think an array is the best structure for your problem.我不认为数组是解决您问题的最佳结构。
You should use some graph data structure (with networkx for example ) and use algorithm like the Dijkstra one's or A* (derivated from the first one).您应该使用一些图形数据结构(例如 networkx )并使用像Dijkstra one's或A* (源自第一个)的算法。
The Dijkstra algorithm is implemented in netwokrkx ( function for shortest path ). Dijkstra 算法在 netwokrkx( 最短路径函数)中实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.