FatMouse and Cheese HDU

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int n,k;
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int dp[101][101],mp[101][101];
bool check(int x,int y)
{
    if(x<1||x>n||y<1||y>n)
        return false;
    else
        return true;
}
int dfs(int x,int y)
{
    int ans=0;
    if(!dp[x][y])
    {
        for(int j=1;j<=k;j++)
        {
            for(int i=0;i<4;i++)
            {
                int xx=x+dir[i][0]*j;
                int yy=y+dir[i][1]*j;
                if(check(xx,yy)&&mp[xx][yy]>mp[x][y]) 
                        ans=max(ans,dfs(xx,yy));
                else
                    continue;
            }
        }
        dp[x][y]=ans+mp[x][y];
    }
    return dp[x][y];
}
int main()
{
    while(scanf("%d%d",&n,&k))
    {
        if(n==-1&&k==-1)
            break;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&mp[i][j]);
        //初始化 
        memset(dp,0,sizeof(dp));
        printf("%d
",dfs(1,1));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/QingyuYYYYY/p/12238601.html