最小化初始点(倒推的动态规划)

最小化初始点
Description
Given a grid with each cell consisting of positive, negative or no points i.e, zero points. We can move across a cell only if we have positive points ( > 0 ). Whenever we pass through a cell, points in that cell are added to our overall points. We need to find minimum initial points to reach cell (m-1, n-1) from (0, 0) by following these certain set of rules :

1.From a cell (i, j) we can move to (i+1, j) or (i, j+1).

2.We cannot move from (i, j) if your overall points at (i, j) is <= 0.

3.We have to reach at (n-1, m-1) with minimum positive points i.e., > 0.

Input
The first line contains an integer ‘T’ denoting the total number of test cases.In each test cases, the first line contains two integer ‘R’ and ‘C’ denoting the number of rows and column of array.
The second line contains the value of the array i.e the grid, in a single line separated by spaces in row major order.

Constraints:

1 ≤ T ≤ 30

1 ≤ R,C ≤ 10

-30 ≤ A[R][C] ≤ 30

Input: points[m][n] = { {-2, -3, 3},
{-5, -10, 1},
{10, 30, -5}
};

Output
Print the minimum initial points to reach the bottom right most cell in a separate line.

7

Explanation:
7 is the minimum value to reach destination with
positive throughout the path. Below is the path.

(0,0) -> (0,1) -> (0,2) -> (1, 2) -> (2, 2)

We start from (0, 0) with 7, we reach(0, 1)
with 5, (0, 2) with 2, (1, 2) with 5, (2, 2)with and finally we have 1 point (we needed
greater than 0 points at the end).

Sample Input 1
1
3 3
-2 -3 3 -5 -10 1 10 30 -5

Sample Output 1
7

# 采用倒推的动态规划
def solution(l, a):
    array = []
    for i in range(0, a * a, a):
        array.append(l[i: i+a])
    # 每个坐标存放的都是刚到达该点时的最小值
    init = [[0] * a for i in range(a)]
    # 初始化右下角点
    if array[-1][-1] >= 0:
        init[-1][-1] = 1
    elif array[-1][-1] < 0:
        init[-1][-1] = 1 - array[-1][-1]
    # 初始化边界点
    for i in range(a - 2, -1, -1):
        init[-1][i] = max(init[-1][i + 1] - array[-1][i], 1)
        init[i][-1] = max(init[i + 1][-1] - array[i][-1], 1)
    # 填充中间内容
    for m in range(a - 2, -1, -1):
        for n in range(a - 2, -1, -1):
            # 转移到右边或者下边所需的最小值
            min_value = min(init[m + 1][n], init[m][n + 1])
            init[m][n] = max(min_value - array[m][n], 1)
    return init[0][0]


if __name__ == '__main__':
    n = int(input())
    for _ in range(n):
        a, b = map(int, input().strip().split())
        l = list(map(int, input().strip().split()))
        result = solution(l, a)
        print(result)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值