我想寫一個算法,它會以最小的代價(每個座標都有一個預先定義的成本)在n * n矩陣中找到路徑。路徑成本被定義爲所有座標成本的總和。第一行輸入包含矩陣的大小,後面的n行是表格行。最後兩行代碼是1.開始座標2.結束座標。輸出是最小路徑成本。最小成本路徑不工作的優化
例輸入:
5
0 1 2 1 1
0 0 1 5 1
1 0 0 1 1
1 1 0 7 0
1 8 0 0 0
0 0
4 4
輸出應爲0
這是memoization的代碼(它的工作原理沒有記憶化,但它的速度慢)
import copy
import sys
sys.setrecursionlimit(9000)
INF = 100000
n = int(input())
memo = {}
def input_matrix(n) :
p = []
for i in range(n) :
p.append(list(map(int, input().split())))
return p
def min_cost(matrix, x, y, end_x, end_y) :
if x == end_x and y == end_y :
return 0
if (x, y) in memo :
return memo[(x, y)]
if x == len(matrix) or y == len(matrix) or x == -1 or y == -1 or matrix[y][x] == -1:
return INF
z = copy.deepcopy(matrix)
z[y][x] = -1
memo[(x, y)] = min(
min_cost(z, x+1, y, end_x, end_y)+matrix[y][x],
min_cost(z, x-1, y, end_x, end_y)+matrix[y][x],
min_cost(z, x, y+1, end_x, end_y)+matrix[y][x],
min_cost(z, x, y-1, end_x, end_y)+matrix[y][x]
)
return memo[(x, y)]
matrix = input_matrix(n)
begin_coords = list(map(int, input().split()))
end_coords = list(map(int, input().split()))
print(min_cost(matrix, begin_coords[0], begin_coords[1], end_coords[0], end_coords[1]))
您可能想要描述一下你在做什麼,並提供一個帶有預期輸出的(小)樣本輸入。 –
此外,如果這是一個不起作用的優化,有沒有這樣的代碼可以在小輸入上正常工作?記憶是你提到的優化嗎? –
代碼無需記憶即可正常工作。 – gimli