首页 > 代码库 > poj 1088 滑雪 【记忆化搜索】+【DFS】

poj 1088 滑雪 【记忆化搜索】+【DFS】

策略:如题

题目链接:http://poj.org/problem?id=1088

代码:

#include<stdio.h>
#include<string.h>
int map[105][105], dp[105][105], n, m;
const int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0}; //四个方向
int limit(int x, int y)  //判断是不是越界了
{
	if(x<1||x>n||y<1||y>m) return 0;
	return 1;
}
int dfs(int x, int y)  查找
{
	if(dp[x][y]) return dp[x][y];  //如果以前找找过了,就不用再找了, 记忆化搜索
	int pre, flag, sum, i;  //flag 是标记周围有没有比他小的高度, pre是储存周围某一方向的长度, sum是选择四个方向最大的长度
	pre = sum = flag = 0;
	for( i =0; i < 4; i ++){
		int nx = x+dir[i][0];
		int ny = y+dir[i][1];
		if( limit(nx, ny)&&map[nx][ny] < map[x][y]){
			pre = dfs(nx, ny);
			sum = sum>pre?sum:pre;
			flag = 1;
		}
	}
	if(flag) dp[x][y] =sum+1;  
	else dp[x][y] = 1;<strong></strong><pre name="code" class="cpp" style="display: inline !important; "><strong style="font-family: Arial, Helvetica, sans-serif; white-space: normal; background-color: rgb(255, 255, 255); "></strong><pre name="code" class="cpp" style="display: inline !important; "><strong style="font-family: Arial, Helvetica, sans-serif; white-space: normal; background-color: rgb(255, 255, 255); "></strong><pre name="code" class="cpp" style="display: inline !important; ">//如果flag == 0,就意味着周围没有比他低的高度, 就将该处赋值为1


return dp[x][y];}int main(){int i, j;while(scanf("%d%d", &n, &m) == 2){for(i = 1; i <= n; i ++)for(j = 1; j<= m; j ++)scanf("%d", &map[i][j]);int max = 0;memset(dp, 0, sizeof(dp)); //初始化for(i = 1; i <= n; i ++)for(j = 1; j <= m; j ++){dp[i][j] = dfs(i, j);// printf("%d..", dp[i][j]);if(max < dp[i][j]) //找最大的max = dp[i][j];}printf("%d\n", max);}return 0;}