骨头的诱惑DFS

ZOJ2110
题目大意:给出起始位置和终点位置,要求在指定的时间刚好到达终点时间,每移动一步一秒,并且不能返回。
   
   
#include <iostream>
#include <math.h>
#define MAXLEN 7
#define MAXTIME 50
using namespace std;
 
char mymap[MAXLEN][MAXLEN];
int dirs[4][2]={{0,-1},{0,1},{1,0},{-1,0}};
int time;
int width,height;
int doori,doorj;
bool escape;
 
void dfs(int locationi,int locationj,int spendtime){
if(locationi>width||locationj>height||locationi<0||locationj<0)
return;
if(locationi==doori&&locationj==doorj&&spendtime==time){
escape = true;
return;
}
//剪枝
int temp = (time-spendtime) - fabs(locationi-doori) - fabs(locationj-doorj);
/**如果abs(x-y)+abs(dx-dy)为偶数,则说明 abs(x-y) 和 abs(dx-dy)的奇偶性相同,需要走偶数步
 
如果abs(x-y)+abs(dx-dy)为奇数,那么说明 abs(x-y) 和 abs(dx-dy)的奇偶性不同,需要走奇数步
 
理解为 abs(si-sj)+abs(di-dj) 的奇偶性就确定了所需要的步数的奇偶性!!
 
而 (ti-setp)表示剩下还需要走的步数,由于题目要求要在 ti时 恰好到达,那么 (ti-step) 与 abs(x-y)+abs(dx-dy) 的奇偶性必须相同
**/
if(temp<0||temp%2)
return;
for(int i=0;i<4;i++){
if(mymap[locationi+dirs[i][0]][locationj+dirs[i][1]] != 'X'){
mymap[locationi+dirs[i][0]][locationj+dirs[i][1]] = 'X';
dfs(locationi+dirs[i][0],locationj+dirs[i][1], spendtime+1);
if(escape)
return;
//恢复现场
mymap[locationi+dirs[i][0]][locationj+dirs[i][1]] = '.';
}
}
}
/**
3 4 5
S...
.X.X
...D
YES
4 4 8
.X.X
..S.
....
DX.X
YES
4 4 5
S.X.
..X.
..XD
....
NO
0 0 0
 
**/
int main()
{
int starti,startj;
int wall;
while(cin>>width>>height>>time,width,height,time){
wall = 0;
for(int i=0;i<width;i++){
for(int j=0;j<height;j++){
cin>>mymap[i][j];
switch(mymap[i][j]){
case 'S':
starti = i;
startj = j;
break;
case 'D':
doori = i;
doorj = j;
break;
case 'X':
wall ++;
break;
default:
break;
}
}
}
//若能够活动的地方小于给的时间是肯定无法逃脱
if(width*height-wall<time)
cout<<"No"<<endl;
escape = false;
mymap[starti][startj] = 'X';
dfs(starti, startj, 0);
if(escape)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值