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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章