Description
Given a square grid of size n, each cell of which contains integer cost which represents a cost to traverse through that cell, we need to find a path from top left cell to bottom right cell by which total cost incurred is minimum.
Note : It is assumed that negative cost cycles do not exist in input matrix.
Input
The first line of input will contain number of test cases T. Then T test cases follow . Each test case contains 2 lines. The first line of each test case contains an integer n denoting the size of the grid. Next line of each test contains a single line containing N*N space separated integers depecting cost of respective cell from (0,0) to (n,n).
Constraints:1<=T<=50,1<= n<= 50
Output
For each test case output a single integer depecting the minimum cost to reach the destination.
Sample Input 1
2
5
31 100 65 12 18 10 13 47 157 6 100 113 174 11 33 88 124 41 20 140 99 32 111 41 20
2
42 93 7 14
Sample Output 1
327
63
注: 该算法针对于只能向下和向右移动.
def solution(array, n):
# 初始化动态规划数组
dp = [[0] * n for i in range(n)]
dp[0][0] = array[0][0]
# 填充动态规划数组边缘
for i in range(1, n):
dp[0][i] = dp[0][i - 1] + array[0][i]
dp[i][0] = dp[i - 1][0] + array[i][0]
for m in range(1, n):
for p in range(1, n):
dp[m][p] = min(dp[m - 1][p], dp[m][p - 1]) + array[m][p]
return dp[-1][-1]
if __name__ == '__main__':
n = int(input())
for _ in range(n):
number = int(input())
l = list(map(int, input().strip().split()))
array = []
for i in range(0, len(l), number):
array.append(l[i: i+number])
result = solution(array, number)
print(result)