1. At the beginning, the title was wrong, and I searched it with wide search. You must arrive at the destination in t seconds, not early to late.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int n,m,t,step,flag;
char map_[10][10];
int dir[4][2]= {
{
-1,0},{
1,0},{
0,-1},{
0,1}};
int vis[10][10];
struct node
{
int x;
int y;
};
int judging(int x, int y)
{
if(x>=0&&x<n&&y>=0&&y<m&&(map_[x][y]=='.'||map_[x][y]=='D'))
{
return 1;
}
return 0;
}
int dfs(struct node s,struct node e,int step)
{
if(step>t)
{
return 0;
}
if(map_[s.x][s.y]==map_[e.x][e.y]&&step==t)//忽略了,必须是刚刚好t秒到终点才算成功!
{
flag=1;
return 0;
}
if(flag)
{
return 0;
}
int xx,yy;
for(int i=0; i<4; i++)
{
xx=s.x+dir[i][0];
yy=s.y+dir[i][1];
if(judging(xx,yy)&&!vis[xx][yy])
{
struct node s1;
s1.x=xx;
s1.y=yy;
vis[xx][yy]=1;
dfs(s1,e,step+1);
vis[xx][yy]=0;
}
}
//cout<<endl;
return 0;
}
int main()
{
int flag1,flag2,xx,yy;
struct node s,e;
s.x=0;
s.y=0;
while(scanf("%d%d%d",&n,&m,&t)&&(n+m+t))
{
step=0;
flag=0;
memset(vis, 0, sizeof(vis));
flag1=0;
flag2=0;
for(int i=0; i<n; i++)
{
scanf("%s",map_[i]);
}
//cout<<"------"<<endl;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
//cout<<"map="<<map_[i][j]<<endl;
if(map_[i][j]=='S')
{
s.x=i;
s.y=j;
}
else if(map_[i][j]=='D')
{
e.x=i;
e.y=j;
}
}
}
if (abs(s.x - e.x) + abs(s.y - e.y) > t || (e.x + s.x + e.y + s.y + t) % 2 == 1)
{
//奇偶剪枝
printf("NO\n");
continue;
}
vis[s.x][s.y]=1;
if(s.x==e.x&&s.y==e.y)
{
printf("YES\n");
}
else
{
dfs(s,e,step);
}
if(flag==1)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
}