记忆化搜索 HDU FatMouse and Cheese

FatMouse and Cheese

题目大意:有只老鼠在一块n*n的土地的每一个坐标里都藏了食物,它最开始在左上角,他想尽可能吃多的食物,但是它下一次要去的坐标上的食物必须比当前坐标多才行,而且每次最多走k格。问这只大老鼠能吃掉最多多少食物。
dp[ i ][ j ]表示以 i , j 为起点能吃最多的食物(没有固定终点在哪里,注意到,如果(i,j)点的周围都比它小,那么(i,j)就是终点了)通过手动模拟发现,其实直接暴力DFS多出来许多不必要的枝,因为会有一些点之间被搜索过,我们就没必要再搜索一次了,我们只需要记录搜索过的点的最大值把它记录下来就好了,下次再搜索到这个点就直接取出来用就行了。这就是记忆化搜索。
代码:

#include<cstdio>
#include<set>
#include<map>
#include<string.h>
#include<string>
#include<vector>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=1e2+10;
int n,k,mp[maxn][maxn],dp[maxn][maxn];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
void init()
{
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++){
        scanf("%d",&mp[i][j]);
        dp[i][j]=0;
    }
}

int check(int x,int y)
{
    if(x<1||x>n||y<1||y>n)return 0;
    else return 1;
}
int dfs(int x,int y)
{
    int ans=0;
    if(dp[x][y])return dp[x][y];//如果已经被搜索过了,就直接返回
    for(int i=0;i<4;i++){//这两重循环就是对(x,y)周围可走的点进行遍历搜索,找到最大值
        for(int j=1;j<=k;j++){//模拟不能超过k格
            int nx=x+dx[i]*j;//下一步坐标
            int ny=y+dy[i]*j;
            if(check(nx,ny)&&mp[nx][ny]>mp[x][y]){
                ans=max(ans,dfs(nx,ny));//递归找最大值,当(x,y)是终点时,就是递归出口
            }
        }
    }
    return dp[x][y]=ans+mp[x][y];
}


int main()
{
    while(scanf("%d%d",&n,&k)&&n+k!=-2){
        init();
        printf("%d\n",dfs(1,1));
    }
    return 0;
}

发布了34 篇原创文章 · 获赞 7 · 访问量 1896

猜你喜欢

转载自blog.csdn.net/qq_43628761/article/details/95096438