动态规划:二维DP
N*M个方格,每格有一定苹果,从左上角开始,能捡到多少苹果
S[i][j] = A[i][j] + max{S[i][j-1],S[i-1][j]} 注意边界条件
并打印路径:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {//注意while处理多个case
int m = in.nextInt();
int n = in.nextInt();
int[][] arr = new int[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
arr[i][j] = in.nextInt();
}
}
int[][] result = new int[m][n];
int[][] path = new int[m][n];
path[0][0] = 1;
result[0][0] = arr[0][0];
for(int i = 1; i < n; i++){
result[0][i] = result[0][i-1] + arr[0][i];
}
for(int i = 1; i < m; i++){
result[i][0] = result[i-1][0] + arr[i][0];
}
for(int i = 1; i < n; i++){
path[0][i] = 1;
}
for(int i = 1; i < m; i++){
path[i][0] = 0;
}
for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
if((i == 0 && j==0) || (i==1 && j==0) || (i==0 && j==1)) continue;
int big = 0;
int p = 0;
if(result[i][j-1]>result[i-1][j]){
big = result[i][j-1];
p = 1;
}else{
big = result[i-1][j];
p = 0;
}
path[i][j] = p;
result[i][j] = arr[i][j] + big;
}
}
int a = m-1, b = n-1;
int[] road = new int[a+b+1];
for(int i = a+b; i >= 0; i--){
road[i] = arr[a][b];
if(path[a][b] == 1){
b--;
}else a--;
}
System.out.println(Arrays.toString(road));
}
}
}