#include <iostream>
#include <istream>
#include <sstream>
#include <vector>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <cstring>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <ctime>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <iomanip>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <iterator>
using namespace std;
const int maxn = 30, INF = 1e9 + 7, dir[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };
int f[maxn][maxn][4][5],n,m,sx,sy,ex,ey,ans;
char ch[maxn][maxn];
struct Node {
int x, y, face, color, cnt;
Node(int _x, int _y) :x(_x), y(_y) {
cnt = 0;
face = 0;
color = 0;
}
};
int bfs() {
int cnt = 0;
queue<Node> q;
Node node(sx, sy);
q.push(node);
f[sx][sy][0][0] = 0;
while (!q.empty()) {
int len = q.size();
for (int i = 0; i < len; i++) {
node = q.front();
q.pop();
if (node.x == ex && node.y == ey && node.color == 0) {
return cnt;
}
Node tmp = node;
tmp.x = node.x + dir[node.face][0];
tmp.y = node.y + dir[node.face][1];
tmp.color = (node.color + 1) % 5;
if (tmp.x >= 0 && tmp.x < n && tmp.y >= 0 && tmp.y < m && ch[tmp.x][tmp.y] != '#' && f[tmp.x][tmp.y][tmp.face][tmp.color] == -1) {
f[tmp.x][tmp.y][tmp.face][tmp.color] = f[node.x][node.y][node.face][node.color] + 1;
q.push(tmp);
}
tmp = node;
tmp.face = (node.face + 1) % 4;
if (tmp.x >= 0 && tmp.x < n && tmp.y >= 0 && tmp.y < m && f[tmp.x][tmp.y][tmp.face][tmp.color] == -1) {
f[tmp.x][tmp.y][tmp.face][tmp.color] = f[node.x][node.y][node.face][node.color] + 1;
q.push(tmp);
}
tmp.face = (node.face + 3) % 4;
if (tmp.x >= 0 && tmp.x < n && tmp.y >= 0 && tmp.y < m && f[tmp.x][tmp.y][tmp.face][tmp.color] == -1) {
f[tmp.x][tmp.y][tmp.face][tmp.color] = f[node.x][node.y][node.face][node.color] + 1;
q.push(tmp);
}
}
cnt++;
}
return INF;
}
int main()
{
int kCase = 0;
while (cin >> n >> m && m && n) {
ans = INF;
memset(f, -1, sizeof(f));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> ch[i][j];
if (ch[i][j] == 'S') {
sx = i;
sy = j;
}
else if (ch[i][j] == 'T') {
ex = i;
ey = j;
}
}
}
int ans = bfs();
if (kCase)cout << endl;
cout << "Case #" << ++kCase << endl;
if (ans == INF) cout << "destination not reachable" << endl;
else cout << "minimum time = "<< ans<<" sec" << endl;
}
return 0;
}
uva10047
最新推荐文章于 2024-09-27 11:26:03 发布