简体   繁体   中英

Minimal cost path of 2d matrix

I am trying to find the minimal cost path from point (0, 0) to point {(u, v) |u + v <= 100} in a 2d matrix of data I have generated.

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. data contains the "cost" of stepping on its cell, and total_cost_arr is used to assist reconstructing the path.

I think that placing (i,j) in previous cell is causing some conflicts which lead to this behavior.

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

The Dijkstra algorithm is implemented in netwokrkx ( function for shortest path ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM