簡體   English   中英

二維矩陣的最小成本路徑

[英]Minimal cost path of 2d matrix

我試圖找到從點 (0, 0) 到點 {(u, v) | 的最小成本路徑 u + v <= 100} 在我生成的二維數據矩陣中。

我的算法非常簡單,目前我已經設法產生以下(可視化)結果,這讓我明白我的算法離我很遠。 在此處輸入圖片說明

# 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)

path_arr 的每個單元格都包含路徑中下一個單元格的 (i,j) 元組。 data 包含踩踏其單元格的“成本”,total_cost_arr 用於協助重建路徑。

我認為將 (i,j) 放在前一個單元格中會引起一些沖突,從而導致這種行為。

我不認為數組是解決您問題的最佳結構。

您應該使用一些圖形數據結構(例如 networkx )並使用像Dijkstra one'sA* (源自第一個)的算法。

Dijkstra 算法在 netwokrkx( 最短路徑函數)中實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM