二维矩阵的最小成本路径

问题描述

我试图找到从点(0,0)到点{(u,v)| u + v

我的算法非常简单,目前我设法产生了以下(可视化)结果,这使我理解我的算法还很遥远。

enter image description here

# 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] + data[i][j]:
                path_arr[i - 1,j] = (i,j)
            else:
                path_arr[i,j)

path_arr的每个单元格包含路径中下一个单元格的(i,j)元组。 数据包含踩到其单元格的“成本”,并且 total_cost_arr用于协助重建路径。

我认为将(i,j)放在上一个单元格中会引起一些冲突,从而导致这种行为。

解决方法

我认为数组不是解决您问题的最佳结构。

您应该使用某种图形数据结构(带有networkx for example)并使用诸如Dijkstra one'sA*(源自第一个)的算法。

Dijkstra算法在netwokrkx(function for shortest path)中实现。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...