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)统计X的个数ans,因为走一步用一秒,所以t秒就是t步,如果n * m- ans < t的话,可以到达的点的数量比走的步数少,则不可能到达出口。这个剪枝在这道题可以省掉很多时间(当然如果换一批测试数据效果应该就不一样了)。
(2)第二个是很关键的奇偶剪枝。
假设在某一时刻t,狗狗走到P(xi, yi),又记终点为D(x0, y0)。由P到D的路径可以分解为水平方向和竖直方向(类似于高中物理的位移的正交分解),就是说将P到D的每一条可行路径分解为从直线x = xi到达x = x0,和由直线y = yi到直线y = y0的两个分路径。现在考虑由x = xi到x = x0,当x0 - xi为偶数时,说明x0和xi的奇偶性相同,那么无论通过怎么样的路径由x = xi到x = x0,路径的步数总和必定为偶数(因为每走一步所处方位的x坐标奇偶性就变一次),不然不可能到达x0,,同理,当x0 - xi为奇数时,无论走什么路径,步数总和必为奇数。考查由xi到x0之后,yi到y0的情况不言而知。设由xi到x0的步数为tx,由yi到y0的步数为ty,则tx和ty的奇偶性分别与abs(xi - x0)和abs(yi - y0)的相同,所以总步数tx + ty的奇偶性和abs(xi - x0) + abs(yi - y0)的奇偶性相同。注意,总步数tx + ty实际上就是在P点时剩余的时间t。由此可知,由P到D的总步数,也就是剩余的时间t的奇偶性必定与abs(xi - x0) + abs(yi - y0)的奇偶性相同。不然就无法从P到达D。
(3)最短路径剪枝。
由某一点P(xi, yi)到终点D(x0, y0),最短路径恰恰是上面提到的abs(xi - x0) + abs(yi - y0),这也就是由P到D所需的最短时间,如果它大于当前剩余的时间,就不能到达D。
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
int n,m;
int fx[4]={-1,1,0,0},fy[4]={0,0,-1,1}; //四个方位用来移动点。
char s[10][10]; // 存放迷宫地图。
struct point{
int x,y;
}ss,e; //记录起点和终点坐标。
int jiou(int i,int j)
{
return abs(i-e.y)+abs(j-e.x); //奇偶校验,判断这个点有无到达终点的可能。
}
bool dfs(int x,int y,int t)
{
if(t==0) return 0;
int a=jiou(x,y);
if((a&1)!=(t&1)||a>t) return 0;
int xx,yy,i;
for(i=0;i<4;i++)
{
xx=x+fx[i];
yy=y+fy[i];
if(xx>=0&&yy>=0&&xx<n&&yy<=m&&s[xx][yy]!='X'){
if(s[xx][yy]=='D'&&t==1){ //因为是要求恰好在t时到达 ,t=1。
return 1;
}
if(s[xx][yy]=='.'){
s[xx][yy]='X';
if(dfs(xx,yy,t-1)) return 1;
s[xx][yy]='.';
}
}
}
return 0;
}
int main()
{
int t;
while(~scanf("%d%d%d",&n,&m,&t)&&(n||m||t)){
int ans=1,i,j;
for(i=0;i<n;i++)
scanf("%s",s[i]);
for(i=0;i<n;i++)
for(j=0;j<m;j++){
if(s[i][j]=='X'){
ans++; //记录X的个数。
}
if(s[i][j]=='S'){
s[i][j]='X';
ss.x=j;
ss.y=i;
}
else if(s[i][j]=='D'){
e.x=j;
e.y=i;
}
}
if(n*m-ans<t||!dfs(ss.y,ss.x,t)) puts("NO");
else puts("YES");
}
}
本文介绍了一个迷宫逃脱问题,狗狗需要在限定时间内找到出口。文章详细解析了算法思路,包括统计障碍物数量、奇偶性剪枝和最短路径剪枝等关键技术点。
398

被折叠的 条评论
为什么被折叠?



