#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <queue>
using namespace std;
int blk[6][6];
int sx, sy, dx, dy;
int n, m, t;
int dist[6][6];
bool Search(int x , int y, int time)
{
if (t-time == 1)
{
return x==dx && abs(dy-y)==1 || y==dy && abs(x-dx)==1 ;
}
else if (t-time < dist[x][y]) return false;
blk[x][y]=1;
if (x>0 && blk[x-1][y]==0 && Search(x-1, y, time+1) ) return true;
if (x<n-1 && blk[x+1][y]==0 && Search(x+1, y , time+1) ) return true;
if (y > 0 && blk[x][y-1]==0 && Search(x, y-1, time+1) ) return true;
if (y<m-1 && blk[x][y+1]==0 && Search(x, y+1, time+1) ) return true;
blk[x][y] = 0;
return false;
}
void CalcDist()
{
queue<int> Q;
int x, y, dis=0;
Q.push(dx);
Q.push(dy);
Q.push(dis);
for (int i =0; i < n; i++)
{
for (int j =0; j <m; j++)
dist[i][j] = 51;
}
dist[dx][dy] =0;
while(!Q.empty())
{
x = Q.front(); Q.pop();
y = Q.front(); Q.pop();
dis = Q.front(); Q.pop();
dis++;
if (x>0 && blk[x-1][y]==0 && dist[x-1][y] == 51){
dist[x-1][y] = dis;
Q.push(x-1);
Q.push(y);
Q.push(dis);
}
if (x<n-1 && blk[x+1][y]==0 && dist[x+1][y] == 51){
dist[x+1][y] = dis;
Q.push(x+1);
Q.push(y);
Q.push(dis);
}
if (y>0 && blk[x][y-1]==0 && dist[x][y-1] == 51){
dist[x][y-1] = dis;
Q.push(x);
Q.push(y-1);
Q.push(dis);
}
if (y<m-1 && blk[x][y+1]==0 && dist[x][y+1] == 51){
dist[x][y+1] = dis;
Q.push(x);
Q.push(y+1);
Q.push(dis);
}
}
for (int i =0; i < n; i++)
{
for (int j =0; j <m; j++)
cout<<setw(2)<<dist[i][j]<<" " ;
cout<<endl;
}
}
int main(int argc, char *argv[])
{
char c;
while(cin>>n>>m>>t, n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
cin>>c;
if ( c=='S' ){ sx = i; sy = j; blk[i][j] = 0;}
else if (c=='X') { blk[i][j]=1; }
else if (c=='D') { dx = i; dy = j; blk[i][j] = 1; }
else if (c=='.') {blk[i][j] = 0; }
}
}
CalcDist();
if (Search(sx, sy, 0)) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
zoj 2110 -- 未解决
最新推荐文章于 2022-02-25 21:57:21 发布