hdu 1010 Tempter of the Bone 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1010
DFS
题目大意:狗走迷宫,给出地图,地图有四种标记,分别是'X'--墙;'.'--平地;'S'--起始点;'D'--终止点。终止点door是个门,在t时刻打开,狗在t时刻到达D点,它就出去了,问狗有没有出去的可能。
题目分析:DFS,简单易懂。需要考虑的地方主要在剪枝,本题我用了两种剪枝,具体看代码。
code:
#include<stdio.h>
#include<string.h>
#include<math.h>
int t,m,n,flag,sx,sy,ex,ey;
char c[8][8];
int abs(int a)
{
if(a>0)return a;
else return a*(-1);
}
void dfs(int x,int y,int step)
{
if(flag)return;
//printf("现在在:c[%d][%d]\n",x,y);
if(x==ex&&y==ey&&step!=t)return;
if(x==ex&&y==ey&&step==t){flag=1;return;}
if(t-step<abs(ex-x)+abs(ey-y)||step==t)return;
c[x][y]='X';
if(x+1<m&&(c[x+1][y]=='.'||c[x+1][y]=='D'))dfs(x+1,y,step+1),c[x+1][y]='.';
if(x-1>=0&&(c[x-1][y]=='.'||c[x-1][y]=='D'))dfs(x-1,y,step+1),c[x-1][y]='.';
if(y+1<n&&(c[x][y+1]=='.'||c[x][y+1]=='D'))dfs(x,y+1,step+1),c[x][y+1]='.';
if(y-1>=0&&(c[x][y-1]=='.'||c[x][y-1]=='D'))dfs(x,y-1,step+1),c[x][y-1]='.';
return;
}
int main()
{
int i,j,step,wall;
char str[10];
while(scanf("%d%d%d",&m,&n,&t)!=EOF&&(m||n||t))
{
wall=flag=0;
getchar();
for(i=0;i<m;i++)
{
scanf("%s",str);
for(j=0;j<n;j++)
{
if(str[j]=='X')wall++;
c[i][j]=str[j];
if(c[i][j]=='S')sx=i,sy=j;
else if(c[i][j]=='D')ex=i,ey=j;
}
}
//printf("奇偶剪枝标志:%s\n",(t-abs(ex-sx)+abs(ey-sy))%2?"剪":"不剪");
if(!((t-abs(ex-sx)+abs(ey-sy))%2)&&n*m-wall-1>=t)
{
dfs(sx,sy,0);
if(flag)printf("YES\n");
else printf("NO\n");
}//如果说所有的可以走的路加起来都比要求的时间小的话,那么肯定到不了了
else printf("NO\n");
}
return 0;
}
//这个题可以:1不用visit数组,2需要奇偶剪枝,3还有最后这种奇葩剪枝。