骨头的诱惑DFS

来源:互联网 发布:局域网网站搭建 ubuntu 编辑:程序博客网 时间:2024/04/27 16:56
ZOJ2110
题目大意:给出起始位置和终点位置,要求在指定的时间刚好到达终点时间,每移动一步一秒,并且不能返回。
详细信息请参见:http://www.cppblog.com/Geek/archive/2010/04/26/113615.html
#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 0
原创粉丝点击