FatMouse has stored some cheese in a city. The city can be considered as a square grid of dimension n: each grid location is labelled (p,q) where 0 <= p < n and 0 <= q < n. At each grid location Fatmouse has hid between 0 and 100 blocks of cheese in a hole. Now he's going to enjoy his favorite food.
FatMouse begins by standing at location (0,0). He eats up the cheese where he stands and then runs either horizontally or vertically to another location. The problem is that there is a super Cat named Top Killer sitting near his hole, so each time he can run at most k locations to get into the hole before being caught by Top Killer. What is worse -- after eating up the cheese at one location, FatMouse gets fatter. So in order to gain enough energy for his next run, he has to run to a location which have more blocks of cheese than those that were at the current hole.
Given n, k, and the number of blocks of cheese at each grid location, compute the maximum amount of cheese FatMouse can eat before being unable to move.
FatMouse begins by standing at location (0,0). He eats up the cheese where he stands and then runs either horizontally or vertically to another location. The problem is that there is a super Cat named Top Killer sitting near his hole, so each time he can run at most k locations to get into the hole before being caught by Top Killer. What is worse -- after eating up the cheese at one location, FatMouse gets fatter. So in order to gain enough energy for his next run, he has to run to a location which have more blocks of cheese than those that were at the current hole.
Given n, k, and the number of blocks of cheese at each grid location, compute the maximum amount of cheese FatMouse can eat before being unable to move.
a line containing two integers between 1 and 100: n and k
n lines, each with n numbers: the first line contains the number of blocks of cheese at locations (0,0) (0,1) ... (0,n-1); the next line contains the number of blocks of cheese at locations (1,0), (1,1), ... (1,n-1), and so on.
The input ends with a pair of -1's.
3 1
1 2 5
10 11 6
12 12 7
-1 -1
37
题意:
从左上角出发,每次上下左右最多可以移动m长度,并且移到的位置的数必须大于当前的数,问走过的数中最大和是多少。为了避免重复搜索浪费时间,所以每次深搜都先判断一下是否存在最优解。
思路:
用DFS开始搜,每次四个方向遍历。再考虑步数最多是m单位长度,每次记录最大值。循环之后让当前的总和加上最大和。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int map[105][105];
int dir[4][2]={0,1,1,0,-1,0,0,-1};
int dp[105][105];
int n,m;
int dfs(int x,int y){
if(dp[x][y]) return dp[x][y];//若存在值(最优)则直接返回,避免重复计算
int maxn=0;
for(int i=0;i<4;i++){
for(int j=1;j<=m;j++)
{
int a=j*dir[i][0]+x;
int b=j*dir[i][1]+y;
if(a>=1 && b>=1 && a<=n && b<=n && map[x][y]<map[a][b]){
int k=dfs(a,b);
maxn=max(maxn,k);
}
}
}
dp[x][y]=maxn+map[x][y];
return dp[x][y];
}
int main()
{
while(~scanf("%d%d",&n,&m)){
if(n==-1&&m==-1)break;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
scanf("%d",&map[i][j]);
dp[i][j]=0;
}
}
dfs(1,1);//从第一个点开始
printf("%d\n",dp[1][1]);
}
return 0;
}