HDU 1010 迷宫问题

41 篇文章 0 订阅
DFS:
剪枝(转):
1:能够走的blocks数小于时间。
2:奇偶性剪枝:
可以把map看成这样:
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
从为 0 的格子走一步,必然走向为 1 的格子
从为 1 的格子走一步,必然走向为 0 的格子 
即: 
 0 ->1或1->0 必然是奇数步 
 0->0 走1->1 必然是偶数步
 
所以当遇到从 0 走向 0 但是要求时间是奇数的,

或者, 从 1 走向 0 但是要求时间是偶数的 都可以直接判断不可达!


#include<iostream>
#include<math.h>
using namespace std;
char map[10][10];
int N,M,T;
int di,dj,escape;
int dir[4][2]={{0,-1},{0,1},{1,0},{-1,0}};
void dfs(int x,int y,int cnt)
{
	if(x>N || y>M || x<1 || y<1 )
		return;
	if(cnt==T && x==di && y==dj)
		escape=1;
	if(escape==1)
		return;
	int temp = (T-cnt) - abs(x-di) - abs(y-dj); 
	if(temp<0 || temp &1) //判断奇偶,剪枝
		return; 
	for(int i=0;i<4;i++) //四个方向,堵住回去的路
	{
		if(map[x+dir[i][0]][y+dir[i][1]]!='X')
		{
			map[x + dir[i][0]][y + dir[i][1]]='X';
			dfs(x + dir[i][0], y + dir[i][1], cnt+1);
			map[x+dir[i][0]][y+dir[i][1]]='.'; //恢复回去
		}
	}
	return;
}
int main()
{
	while(cin>>N>>M>>T, N)
	{
		int wall=0;
		int si,sj;
		for(int i=1;i<=N;i++)
			for(int j=1;j<=M;j++)
			{      
				cin>>map[i][j];
				if(map[i][j]=='S')
				{      
					si=i;
					sj=j;
				}
				else if(map[i][j]=='D')
				{
					di=i; 
					dj=j;
				}
				else if(map[i][j]=='X')
					wall++;
			}
			if(T>=M*N-wall)
			{      
				cout<<"NO"<<endl;
				continue;
			}
			map[si][sj]='X';
			escape=0;
			dfs(si,sj,0);
			if(escape==1)
				cout<<"YES"<<endl;
			else
				cout<<"NO"<<endl;
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值