题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1010
做这道题目的时候需要注意剪枝,如果没有剪枝的话,就会超时
注意奇偶剪枝
代码:】
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char map[20][20];
int top[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int sx,sy,ex,ey,t,n,m;
int flag;
int temp;
void dfs(int x,int y,int cas){
int i,k,fx,fy;
//flag=0;
if(cas==t){
if(x==ex&&y==ey)
flag=1;
return;
}
if(flag) return;
temp=abs(x-ex)+abs(y-ey)-abs(cas-t);
if(temp>0||temp&1) return ; //这个剪枝让我想了一个晚上,每次都会变化两步。。
for(k=0;k<4;k++){
fx=x+top[k][0];
fy=y+top[k][1];
if(fx>0&&fx<=n&&fy>0&&fy<=m&&map[fx][fy]!='X'){
map[fx][fy]='X';
dfs(fx,fy,cas+1);
map[fx][fy]='.';
}
}
}
int main(){
int wall;
int i,j,k;
while(~scanf("%d%d%d",&n,&m,&t),n||m||t){
wall=0;
getchar();
for(i=1;i<=n;i++){
for(j=1;j<=m;j++){
scanf("%c",&map[i][j]);
if(map[i][j]=='X')
wall++;
else if(map[i][j]=='S')
{
map[i][j]='X';
sx=i;
sy=j;
}
else if(map[i][j]=='D'){
ex=i;
ey=j;
}
}
getchar();
}
if(n*m-wall<t)
{
printf("NO\n");
continue;
}
flag=0;
dfs(sx,sy,0);
if(flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}