BFS,对于搜索中的每一点,向四周扫描,标记在某点的状态。
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <queue>
using namespace std;
const int maxn = 120;
char Map[maxn][maxn];
int vis[maxn][maxn][2][2];
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int n,m,time,sx,sy;
struct Node {
int x,y,t;
int d,e;
};
//扫描某点的四个方向。
void check(Node &tmp) {
int tx,ty;
for(int i = 0; i < 4; i++) {
tx = tmp.x;
ty = tmp.y;
while(true) {
tx = tx + dir[i][0];
ty = ty + dir[i][1];
if(tx<1 || tx>n || ty<1 || ty>m) {
break;
}
if(Map[tx][ty]=='D') {
tmp.d = 1;
break;
}
if(Map[tx][ty]=='E') {
tmp.e = 1;
break;
}
if(Map[tx][ty]=='X') {
break;
}
}
}
}
int bfs() {
Node cur,nex;
queue<Node>qu;
cur.x = sx;
cur.y = sy;
cur.t = 0;
cur.d = 0;
cur.e = 0;
memset(vis,0,sizeof(vis));
vis[sx][sy][0][0] = 1;
qu.push(cur);
while(!qu.empty()) {
cur = qu.front();
qu.pop();
if(cur.t > time) continue;
check(cur);
if(cur.d && cur.e) return cur.t;
for(int i = 0; i < 4; i++) {
nex.x = cur.x + dir[i][0];
nex.y = cur.y + dir[i][1];
nex.t = cur.t + 1;
nex.d = cur.d;
nex.e = cur.e;
if(nex.x<1 || nex.x>n || nex.y<1 || nex.y>m) continue;
if(vis[nex.x][nex.y][nex.d][nex.e]) continue;
if(Map[nex.x][nex.y] != '.') continue;
vis[nex.x][nex.y][nex.d][nex.e] = 1;
qu.push(nex);
}
}
return -1;
}
int main() {
int T,Case=0;
scanf("%d",&T);
while(T--) {
scanf("%d%d%d",&n,&m,&time);
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= m; j++) {
scanf(" %c",&Map[i][j]);
if(Map[i][j] == 'S') {
sx = i;
sy = j;
}
}
}
int ans = bfs();
printf("Case %d:\n",++Case);
printf("%d\n",ans);
}
return 0;
}