hdu 1078 FatMouse and Cheese 【记忆化搜索+dfs】

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1078

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. 

Input

There are several test cases. Each test case consists of 

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. 

Output

For each test case output in a line the single integer giving the number of blocks of cheese collected. 

Sample Input

3 1
1 2 5
10 11 6
12 12 7
-1 -1

Sample Output

37

题意:给定一个矩阵,老鼠从最左上的位置出发,可以向四个方向行走,但有要求,下一步的cheese必须大于该步,求老鼠能吃到cheese的最大值.

思路:记忆化深搜,记着更新值。我还是有点zz。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 105;
int a[maxn][maxn];
int dp[maxn][maxn];
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};//方向数组
int n,m,ans;
bool check(int x,int y)
{
	if(x>=1&&x<=n&&y>=1&&y<=n)
	  return true;
	return false;
}
int dfs(int x,int y)
{
    if(dp[x][y])//记忆化搜索核心,如果已经搜索过返回 
        return dp[x][y];
    int sum=0;
    for(int i=1;i<=m;i++)//k步
    {
        for(int j=0;j<4;j++)//四个方向
        {
            int xx=x+dir[j][0]*i;
            int yy=y+dir[j][1]*i;
            if(check(xx,yy) && a[xx][yy]>a[x][y])//要求下一个点奶酪大于该点和不越界 
            {
            	int sum1=dfs(xx,yy);
            	if(sum<sum1)
            	   sum=sum1;
			}		
		}
	}
    dp[x][y]=a[x][y]+sum;//能找到的最大值加上当前点的奶酪等于从出发点最多能吃到的cheese 
    return dp[x][y];
}
int main()
{
    while(cin>>n>>m&&(n+m)!=-2)
    {   
        memset(dp,0,sizeof(dp));
        memset(a,0,sizeof(a));
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                cin>>a[i][j];
            }
        }
        ans=dfs(1,1);  //从出发点开始搜索 
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/LOOKQAQ/article/details/81668437