Tempter of the Bone
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 43175 Accepted Submission(s): 11694
The maze was a rectangle with sizes N by M. There was a door in the maze. At the beginning, the door was closed and it would open at the T-th second for a short period of time (less than 1 second). Therefore the doggie had to arrive at the door on exactly the T-th second. In every second, he could move one block to one of the upper, lower, left and right neighboring blocks. Once he entered a block, the ground of this block would start to sink and disappear in the next second. He could not stay at one block for more than one second, nor could he move into a visited block. Can the poor doggie survive? Please help him.
'X': a block of wall, which the doggie cannot enter;
'S': the start point of the doggie;
'D': the Door; or
'.': an empty block.
The input is terminated with three 0's. This test case is not to be processed.
4 4 5 S.X. ..X. ..XD .... 3 4 5 S.X. ..X. ...D 0 0 0
NO YES
这是一道经典搜索题,常规方法是深搜,当然要加上必要的剪枝条件
主要的剪枝条件有:
1、剩余可走区域小于时间
2、奇偶性剪枝
3、越界
4、超时等
下面主要说说奇偶性剪枝
若有一迷宫,将迷宫的每一个位置有0或1表示(x+y为偶数时 为0 否则为1):
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
从图中我们可以很清晰的看出:任意一个位置周围相邻的必然是与本身值相反的值,也就是说,要想走到与本身值相同的点必然要走偶数步;
同理,要想走到与本身相异的值的点必然要走奇数步;
所以,当两个位置的奇偶性相同时(同为0或同为1)若时间为奇数 则必然无法到达;当两个位置的奇偶性不同时(一个为1,另一个为0)若时间为偶数也必不能到达。
我有2种奇偶性剪枝方法
1、
if((S_x+S_y+D_x+D_y+t)%2==1)//剪掉奇数枝
return;
2、
time=T-a-abs(x-D_x)-abs(y-D_y); //time为剩余时间
if(time<0||time%2!=0) //剪掉奇数枝
return;
#include<stdio.h>
#include<string.h>
#include<math.h>
void dfs(int,int,int);
char maze[7][7]; //迷宫
int N,M,T,S_x,S_y,D_x,D_y,i,j,flag,time,wallnumber;
int main()
{
while(scanf("%d%d%d",&N,&M,&T)!=EOF)
{
if(N==0&&M==0&&T==0)
break;
getchar(); //吸收回车 数据不一定安矩阵排列 这里易错
flag=0;
wallnumber=0;
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
scanf("%c",&maze[i][j]);
if(maze[i][j]=='S')
{
S_x=i;
S_y=j; //出发点位置
}
else if(maze[i][j]=='D')
{
D_x=i;
D_y=j; //出口位置
}
else if(maze[i][j]=='X')
wallnumber++; //记录墙的数量
}
getchar(); //吸收回车
}
if(N*M-wallnumber>=T) //当可以走的街区数大于时间才进入搜索
{
dfs(S_x,S_y,0);
}
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
void dfs(int x,int y,int a)
{
if(flag==1)
return;
if(x==D_x&&y==D_y&&a==T)
{
flag=1;
return;
}
time=T-a-abs(x-D_x)-abs(y-D_y); //time为剩余时间
if(time<0||time%2!=0) //剪掉奇数枝
return;
maze[x][y]='X';
if(y>0&&maze[x][y-1]!='X')//左
dfs(x,y-1,a+1);
if(y<M-1&&maze[x][y+1]!='X')//右
dfs(x,y+1,a+1);
if(x>0&&maze[x-1][y]!='X')//上
dfs(x-1,y,a+1);
if(x<N-1&&maze[x+1][y]!='X')//下
dfs(x+1,y,a+1);
maze[x][y]='.'; //恢复环境
}