给定地图,n * m,S为起点,D为终点,X为墙壁,求是否能刚好在t秒时到达出口。
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
#include <cstdlib>
using namespacestd;
const int maxn =8;
char mp[maxn][maxn];
int n,m,t;
bool vis[maxn][maxn];
bool escape = false;
struct point{
int x,y;
};
point s,e;
point pre[maxn][maxn];
void dfs(int x,int y,int d)
{
if (d ==t){
if(x ==e.x && y ==e.y)escape = true;
return ;
}
mp[x][y] =' ';
if(x +1 < n &&mp[x + 1][y] =='.') {dfs(x +1, y, d + 1);if(escape)return;}
if(x -1 >= 0 &&mp[x - 1][y] =='.') {dfs(x -1, y, d + 1);if(escape)return;}
if(y +1 < m &&mp[x][y + 1] =='.') {dfs(x, y +1, d + 1);if(escape)return;}
if(y -1 >= 0 &&mp[x][y - 1] =='.') {dfs(x, y -1, d + 1);if(escape)return;}
mp[x][y] ='.';
}
int main()
{
while (scanf("%d%d%d",&n,&m,&t) != EOF) {
if(n ==0 && m ==0 && t ==0) return0;
getchar();
escape =false;
memset(mp,0, sizeof(mp));
int wall =0;
for (int i =0; i < n; i ++) {
scanf("%s",mp[i]);
for (int j =0; j < m; j ++){
if(mp[i][j] =='S') {s.x = i,s.y = j;mp[i][j] = '.';}
elseif(mp[i][j] =='D') {e.x = i,e.y = j;mp[i][j] = '.';}
elseif(mp[i][j] =='X') wall++;
}
}
bool fg = ((s.x +s.y +e.x +e.y) %2 == t %2 )? 1 :0;//奇偶性剪枝
if(wall +t + 1 >n * m) fg =false;//无路可走
if(!fg) {printf("NO\n");continue;}
memset(vis,0, sizeof(vis));
dfs(s.x,s.y,0);
if (fg &&escape) printf("YES\n");
elseprintf("NO\n");
}
return0;
}