package com.study.dp;
import java.util.Scanner;
public class test6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();// 地图大小
int x = sc.nextInt(), y = sc.nextInt();// 初始化位置
int v = sc.nextInt();// 初始血量
int c = sc.nextInt();// 血量上限
int[][] mat = new int[n + 1][m + 1];// 地图
int[][] dp = new int[n + 1][m + 1];// 到达某个点的最大血量
// 初始化地图
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
mat[i][j] = sc.nextInt();
}
}
dp[x][y] = v;
// 左上出口1,1
for (int i = x; i > 0; i--) {
for (int j = y; j > 0; j--) {
if (i == x && j == y)
continue;
else if (i == x) {
dp[i][j] = dp[i][j + 1] + mat[i][j];
} else if (j == y) {
dp[i][j] = dp[i + 1][j] + mat[i][j];
} else {
dp[i][j] = Math.max(dp[i][j + 1], dp[i + 1][j]) + mat[i][j];
}
if (dp[i][j] > c)
dp[i][j] = c;
else if(dp[i][j] <=0)
dp[i][j] = -100000000;
}
}
// 左下出口 n 1
for (int i = x; i <= n; i++) {
for (int j = y; j >= 1; j--) {
if (i == x && j == y)
continue;
else if (i == x ) {
dp[i][j] = dp[i][j + 1] + mat[i][j];
} else if (j == y ) {
dp[i][j] = dp[i - 1][j] + mat[i][j];
} else {
dp[i][j] = Math.max(dp[i][j + 1], dp[i - 1][j]) + mat[i][j];
}
if (dp[i][j] > c)
dp[i][j] = c;
else if(dp[i][j] <=0)
dp[i][j] = -100000000;
}
}
// 右上出口 1,m
for (int i = x; i >= 1; i--) {
for (int j = y; j <= m; j++) {
if (i == x && j == y)
continue;
else if (i == x ) {
dp[i][j] = dp[i][j - 1] + mat[i][j];
} else if (j == y ) {
dp[i][j] = dp[i + 1][j] + mat[i][j];
} else {
dp[i][j] = Math.max(dp[i][j - 1], dp[i + 1][j]) + mat[i][j];
}
if (dp[i][j] > c)
dp[i][j] = c;
else if(dp[i][j] <=0)
dp[i][j] = -100000000;
}
}
// 右下出口 n m
for (int i = x; i <= n; i++) {
for (int j = y; j <= m; j++) {
if (i == x && j == y)
continue;
else if (i == x ) {
dp[i][j] = dp[i][j - 1] + mat[i][j];
} else if (j == y ) {
dp[i][j] = dp[i - 1][j] + mat[i][j];
} else {
dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]) + mat[i][j];
}
if (dp[i][j] > c)
dp[i][j] = c;
else if(dp[i][j] <=0)
dp[i][j] = -100000000;
}
}
int m1 = Math.max(dp[1][1], dp[n][1]);
int m2 = Math.max(dp[1][m], dp[n][m]);
int max = Math.max(m1, m2);
if(max>0)
System.out.println(max);
else
System.out.println(-1);
}
}
加强版逃生
最新推荐文章于 2024-09-09 14:40:58 发布