格子里的整数

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值