HDU 1078 FatMouse and Cheese

题目地址:点击打开链接

思路:记忆化搜索

AC代码:

#include<iostream>
#include<cstring>

using namespace std;

int a[100][100],b[100][100],n,k;
int x[4] = {-1,1,0,0}, y[4] = {0,0,-1,1};

bool check(int l,int m)
{
	if(l <0 || l>=n || m<0 || m>=n)
		return false;
	return true;
}

int dfs(int l,int m)
{
	if(b[l][m])
		return b[l][m];
	int i,j,max = 0,ans,ll,mm;
	for(i=1; i<=k; i++)//控制走的步数,不能从0开始,会陷入死循环,从0开始也没有意义
	{
		for(j=0; j<4; j++)
		{
			ll = l + i * x[j];
			mm = m + i * y[j];
			if(check(ll,mm) && a[ll][mm] > a[l][m])
			{
				ans = dfs(ll,mm);
				if(ans > max)
					max = ans;
			}
		}
	}
	b[l][m] = a[l][m] + max;
	return b[l][m];
}

int main()
{
	int i,j,sum;
	while(cin>>n>>k)
	{
		sum = 0;
		if(n == -1 && k == -1)
			break;
		memset(b,0,sizeof(b));
		for(i=0; i<n; i++)
		{
			for(j=0; j<n; j++)
			{
				cin>>a[i][j];
			}
		}
		sum = dfs(0,0);
		printf("%d\n",sum);
	}
	return 0;
}


你可能感兴趣的:(HDU 1078 FatMouse and Cheese)