我需要下圖的幫助,我想在 Python 中實作以下邏輯,我是 Python 的新手。

任何幫助表示贊賞。
uj5u.com熱心網友回復:
我建議尋找每一條可能的路徑。鏈接中的一個示例,然后計算每個可能的總和并尋找最小的
import numpy as np
import copy
def findPaths(mat, path,paths, i, j):
# base case
if not mat or not len(mat):
return
(M, N) = (len(mat), len(mat[0]))
# if the last cell is reached, print the route
if i == M - 1 and j == N - 1:
paths.append(copy.deepcopy(path [[i,j]] ))
return
# include the current cell in the path
path.append( [i,j])
# move right
if 0 <= i < M and 0 <= j 1 < N:
findPaths(mat, path,paths, i, j 1)
# move down
if 0 <= i 1 < M and 0 <= j < N:
findPaths(mat, path,paths, i 1, j)
# backtrack: remove the current cell from the path
path.pop()
if __name__ == '__main__':
mat = [ [2,5,4],
[3,2,1],
[8,0,3] ]
path = []
paths = []
x = y = 0
#find all possible paths
findPaths(mat, path,paths, x, y)
print(paths)
#get the sum of all paths
All_sums = []
for path in paths:
one_sum = 0
for p in path:
one_sum = mat[p[0]][p[1]]
All_sums.append(one_sum)
print(All_sums)
#get lower path
min_path = np.argmin(All_sums)
print(min_path)
#print the path
print(paths[min_path])
#print the val sequence
print([mat[p[0]][p[1]] for p in paths[min_path]])
uj5u.com熱心網友回復:
我們可以通過使用遞回輕松解決這個問題。這個想法是從矩陣的左上角單元格開始,并為下一個節點(緊鄰的右側或緊鄰的底部單元格)回圈,并繼續為每個訪問的單元格執行此操作,直到到達目的地。還要維護一個路徑陣列來存盤當前路徑中的節點,并在訪問任何單元格時更新路徑陣列(包括當前節點)。現在,只要到達目的地(右下角),就列印路徑陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483829.html
