分析:一道简单的dp题,就是找到从上到下每行取一个点,使之联通且和最小,联通就是指 8个方向联通。
dp[i][j] 表示从下到上 以 i,j为终点的最小的联通线。从最后一行到最上面一行dp。然后找到最小的值,从上往下找如果
dp[i][j] == dp[i+1][k] + a[i][j]( k = j-1, j, j+1)则往这个方向走,记得从右往左找。因为相同大小取最右边。
代码:
#include<cstdio>
#include<iostream>
using namespace std;
const int N = 105;
const int INF = 1<<30;
int a[N][N];
int dp[N][N];
int main(){
// freopen("5092.txt", "r", stdin);
int T, m, n;
scanf("%d", &T);
for(int cas = 1; cas <= T; cas++){
printf("Case %d\n", cas);
scanf("%d%d", &n, &m);
for(int i = 0; i <= n+1; i++) dp[i][0] = dp[i][m+1] = INF;
for(int i = 0; i <= m+1; i++) dp[0][i] = dp[n+1][i] = INF;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
scanf("%d", &a[i][j]);
}
}
for(int i = 1; i <= m; i++) dp[n][i] = a[n][i];
for(int i = n-1; i >= 1; i--){
for(int j = 1; j <= m; j++){
dp[i][j] = min(min(dp[i+1][j-1],dp[i+1][j]), dp[i+1][j+1]) + a[i][j];
}
}
int index = 1;
for(int i = 2; i <= m; i++){
if(dp[1][i] <= dp[1][index]) index = i;
}
for(int i = 1; i <= n; i++){
printf("%d%c", index, " \n"[i==n]);
if(i == n) break;
for(int j = 1; j >= -1; j--){
if(dp[i][index] - a[i][index] == dp[i+1][index+j]){
index += j;
break;
}
}
}
}
return 0;
}