HDU1078(记忆化搜索)

#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

int n,k,dp[101][101],map[101][101];

int dfs(int a,int b){
    if(dp[a][b]) return dp[a][b];
    dp[a][b] = map[a][b];
    for(int i = 1;i<=k;i++){
        if(a+i<n&&map[a+i][b]>map[a][b])
            dp[a][b] = max(dp[a][b],dfs(a+i,b)+map[a][b]);
        if(a-i>=0&&map[a-i][b]>map[a][b])
            dp[a][b] = max(dp[a][b],dfs(a-i,b)+map[a][b]);
        if(b-i>=0&&map[a][b-i]>map[a][b])
            dp[a][b] = max(dp[a][b],dfs(a,b-i)+map[a][b]);
        if(b+i<n&&map[a][b+i]>map[a][b])
            dp[a][b] = max(dp[a][b],dfs(a,b+i)+map[a][b]);
    }
    return dp[a][b];
}

int main(void){
    while(scanf("%d %d",&n,&k)!=EOF){
        if(n==-1&&k==-1) break;
        for(int i = 0;i<n;i++){
            for(int j = 0;j<n;j++)
                scanf("%d",&map[i][j]);
        }
        memset(dp,0,sizeof(dp));
        printf("%d\n",dfs(0,0));
    }
}

你可能感兴趣的:(HDU1078(记忆化搜索))