最小化初始点
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)