二维矩阵的最小成本路径

问题描述

我试图找到从点(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)放在上一个单元格中会引起一些冲突,从而导致这种行为。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)