#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<algorithm>
#define For(i,j,k) for (int i=j;i<=k;i++)
#define update(x) (x=='X'?1:0)
#define abs(x) ((x)>0?(x):-(x))
using namespace std;
const int dmax=1010,d[5][2]={{0,0},{1,0},{0,1},{-1,0},{0,-1}},INF=1000000000;
int a[dmax][dmax],sx,sy,ex,ey,n,m,t,ans;
bool p[dmax][dmax],pd[dmax][dmax];
struct node{
int x,y;
node(){
x=y=0;
}
};
struct node q[dmax*dmax];
int dist(int x,int y){ return abs(ex-x)+abs(ey-y); }
bool bfs(){
int f=0,l=1;
q[1].x=sx;
q[1].y=sy;
p[sx][sy]=1;
while (f<l){
f++;
For(i,1,4){
int tx=q[f].x+d[i][0],ty=q[f].y+d[i][1];
if (tx<1 || ty<1 || tx>n || ty>m || pd[tx][ty] || a[tx][ty]) continue;
if (tx==ex && ty==ey)
return 1;
q[++l].x=tx;
q[l].y=ty;
pd[tx][ty]=1;
}
}
return 0;
}
void dfs(int x,int y,int s){
if (ans==1) return;
if (x==ex && y==ey){
if (s==t)
ans=1;
return;
}
if (s>=t)
return;
if (dist(x,y)>t-s)
return;
For(i,1,4){
int tx=x+d[i][0],ty=y+d[i][1];
if (!p[tx][ty] && !a[tx][ty] && tx>=1 && ty>=1 && tx<=n && ty<=m){
p[tx][ty]=1;
dfs(tx,ty,s+1);
p[tx][ty]=0;
}
}
}
int main(){
char c;
while (scanf("%d%d%d",&n,&m,&t)!=EOF){
int sum=0;
sx=sy=ex=ey=ans=0;
memset(p,0,sizeof(p));
memset(pd,0,sizeof(pd));
if (n+m+t==0)
return 0;
getchar();
For(i,1,n){
For(j,1,m){
c=getchar();
a[i][j]=update(c);
if (c=='S'){
sx=i;
sy=j;
}
if (c=='D'){
ex=i;
ey=j;
}
sum+=a[i][j]==0;
}
getchar();
}
if (t%2!=dist(sx,sy)%2){
puts("NO");
continue;
}
if (t>=sum || !bfs()){
puts("NO");
continue;
}
p[sx][sy]=1;
dfs(sx,sy,0);
if (ans)
puts("YES");
else puts("NO");
}
return 0;
}
HDU1010 DFS+剪枝水题
最新推荐文章于 2023-03-22 07:54:35 发布