HDU 1010 深搜+剪枝

剪枝有些多导致我超时两次,一开始想到用广搜但是发现不行,因为这一题要求的是在特定的时间点到达

迷宫出口,用广搜找的的是最快到达出口的时间.

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
char maps[10][10];
int res,total;
int width,length,time;
int sx,sy,ex,ey;
int dir[4][2] = {-1,0,1,0,0,-1,0,1};
void dfs(int x,int y,int t)
{
	int i;
	int bx,by;

	int temp=time-t-abs(ex-x)-abs(ey-y);
    
	//判断是否找到
	if(t==time&&maps[x][y]=='D')
	{
		res=1;return ;
	}

	//到达门口时没有到指定时间也是NO
	if(maps[x][y] == 'D')return;

	//奇偶剪枝
	if(temp<0||temp%2!=0)
        return ;
	for(i=0;i<4;i++)
	{
		bx = x+dir[i][0];by = y+dir[i][1]; 

		//注意控制边界
		if(bx>=1&&bx<=width&&by>=1&&by<=length)
		{
			if(maps[bx][by] == 'X')continue;
			else if(maps[bx][by] == 'D'&&t+1==time){res=1;return;}
			else if(maps[bx][by] == '.')
			{
				maps[bx][by] = 'X';
				dfs(bx,by,t+1);
				if(res)return ;
				maps[bx][by] = '.';
			}
		}
	}
}
int main()
{
	int i,k;
	while(scanf("%d%d%d",&width,&length,&time)&&(width||length||time))
	{
		total = 0;

		for(i=1;i<=width;i++)
		{
			for(k=1;k<=length;k++)
			{
				cin>>maps[i][k];

				if(maps[i][k] == 'S')
				{sx=i;sy=k;}
				else if(maps[i][k] == 'D')
				{ex=i;ey=k;}
				else if(maps[i][k] == 'X')
					total ++;
			}
		}
		res = 0;

		if(width*length - total < time)			//路径剪枝
			cout<<"NO"<<endl;
		else if(sx==ex&&sy==ey&&time==0)		//出发点就是出口且时间为0直接输出YES
			cout<<"YES"<<endl;
		else if(sx==ex&&sy==ey&&time!=0)		//出发点就是出口且时间不为0直接输出NO
			cout<<"NO"<<endl;
		else if(maps[sx][sy] == 'X')			//出发点就是墙更没的说了
			cout<<"NO"<<endl;
		else
		{
			dfs(sx,sy,0);
			if(res)
				cout<<"YES"<<endl;
			else
				cout<<"NO"<<endl;
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值