Topic Source: http://acm.hdu.edu.cn/showproblem.php?pid=1078
Meaning of the questions: from (1,1) to start you can only walk a straight line, a distance of not more than k, plus the value of the grid went on a grid, ask the greatest value.
The first written bfs found Memory Limit, in order to reduce space on the queue marked prevent multiple re-entry queue to go, you can cancel the mark when the queue.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<map>
#include<algorithm>
#include<queue>
#define MAX_len 50100*4
using namespace std;
typedef long long ll;
int a[110][110];
int dp[110][110];
int book[110][110];
struct A {
int x,y;
};
int main()
{
int n,k;
while(scanf("%d %d",&n,&k)!=EOF)
{
memset(book,0,sizeof(book));
queue<A>hh;
if(n==-1&&k==-1)
break;
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
}
}
memset(dp,0,sizeof(dp));
dp[1][1]=a[1][1];
A head;
head.x=1;
head.y=1;
hh.push(head);
while(!hh.empty())
{
head=hh.front();
// printf("%d %d\n",head.x,head.y);
for(i=1;i<=k;i++)
{
int xx=head.x+i;
int yy=head.y;
if(xx<1||yy<1||xx>n||yy>n||a[xx][yy]<=a[head.x][head.y])
{
continue;
}
dp[xx][yy]=max(dp[xx][yy],dp[head.x][head.y]+a[xx][yy]);
A tail;
tail.x=xx;
tail.y=yy;
if(!book[xx][yy])
{
hh.push(tail);
book[xx][yy]=1;
}
}
for(i=1;i<=k;i++)
{
int xx=head.x-i;
int yy=head.y;
if(xx<1||yy<1||xx>n||yy>n||a[xx][yy]<=a[head.x][head.y])
{
continue;
}
dp[xx][yy]=max(dp[xx][yy],dp[head.x][head.y]+a[xx][yy]);
A tail;
tail.x=xx;
tail.y=yy;
if(!book[xx][yy])
{
hh.push(tail);
book[xx][yy]=1;
}
}
for(i=1;i<=k;i++)
{
int xx=head.x;
int yy=head.y+i;
if(xx<1||yy<1||xx>n||yy>n||a[xx][yy]<=a[head.x][head.y])
{
continue;
}
dp[xx][yy]=max(dp[xx][yy],dp[head.x][head.y]+a[xx][yy]);
A tail;
tail.x=xx;
tail.y=yy;
if(!book[xx][yy])
{
hh.push(tail);
book[xx][yy]=1;
}
}
for(i=1;i<=k;i++)
{
int xx=head.x;
int yy=head.y-i;
if(xx<1||yy<1||xx>n||yy>n||a[xx][yy]<=a[head.x][head.y])
{
continue;
}
dp[xx][yy]=max(dp[xx][yy],dp[head.x][head.y]+a[xx][yy]);
A tail;
tail.x=xx;
tail.y=yy;
if(!book[xx][yy])
{
hh.push(tail);
book[xx][yy]=1;
}
}
hh.pop();
book[head.x][head.y]=0;
}
int ans=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
ans=max(ans,dp[i][j]);
}
}
printf("%d\n",ans);
}
return 0;
}