1 |
2 |
3 |
|
5 |
4 |
|
|
|
1 |
2 | |
3 | ||
/*
這題要開4維數組,如果你只開3維數組請看上面的那兩個表格,12345代表走的路。
如果開3維的他們的表示有可能是相同的,因爲負數的原因也可能不相同。無論你先
走到哪一個狀態,當你的程序走到另一個狀態的時候,你的程序就會直接返回前一個狀態的值。
這個值就有可能是錯誤的。
開四維數組d[i][j][k][l] i,j代表當前所在位置k代表之前已經走過多少負數,l代表
從哪個方向走進這個位置的。
*/
#include <stdio.h>
#include <string.h>
#define maxn 80
long long n,ne,d[maxn][maxn][7][3],g[maxn][maxn],vis[maxn][maxn][7][3];
int dir[3][2]={0,-1,0,1,1,0};
long long max(long long a,long long b)
{
if(a>b) return a;
else return b;
}
long long dp(int a,int b,int c,int e)
{
long long &res=d[a][b][c][e];
long long &flag=vis[a][b][c][e];
if(flag) return res;
flag=1;res=-((long long)1<<60);
if(c>ne) return res;
if(a==n&&b==n)
{
if(g[a][b]<0)
c++;
if(c<=ne)
res=g[a][b];
return res;
}
for(int i=0;i<3;i++)
{
int newr=a+dir[i][0];
int neww=b+dir[i][1];
int newc=c;
if(g[a][b]<0) newc++;
if(newr>=1&&newr<=n&&neww>=1&&neww<=n&&g[newr][neww]!=((long long)1<<60))
{
int t=g[a][b];
g[a][b]=((long long)1<<60);
long long temp=dp(newr,neww,newc,i);
if(temp!=-((long long)1<<60))
res=max(res,temp+t);
g[a][b]=t;
}
}
return res;
}
int main()
{
// freopen("C:\\Users\\WT\\Desktop\\測試數據.txt","r",stdin);
int tt=0;
while(scanf("%lld%lld",&n,&ne)&&!(n==0&&ne==0))
{
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
scanf("%lld",&g[i][j]);
memset(d,0,sizeof(d));
memset(vis,0,sizeof(vis));
printf("Case %d: ",++tt);
long long temp=dp(1,1,0,0);
if(temp>-((long long)1<<60))
printf("%lld\n",temp);
else
printf("impossible\n");
}
return 0;
}