const int MAXN = 30;
struct Node
{
int x, y, dir, step, time;
Node (int a = 0, int b = 0, int c = 0, int d = 0, int e = 0)
{
x = a, y = b, dir = c, step = d, time = e;
}
} tn;
//点的x坐标,y坐标,方向,车轮颜色
bool vis[MAXN][MAXN][4][5];
char m[MAXN][MAXN];
queue<Node> q;
int kase, a, b, ansx, ansy;
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
void move(int nx, int ny, int nd, int ns, int nt)
{
if (m[nx][ny] != ‘#‘ && !vis[nx][ny][nd][ns % 5])
{
vis[nx][ny][nd][ns % 5] = true;
q.push(Node(nx, ny, nd, ns, nt));
}
}
bool bfs(Node& ans)
{
while (!q.empty())
{
ans = q.front();
q.pop();
if (ans.x == ansx && ans.y == ansy && ans.step % 5 == 0)
return true;
move(ans.x, ans.y, (ans.dir + 3) % 4, ans.step, ans.time + 1);
move(ans.x, ans.y, (ans.dir + 1) % 4, ans.step, ans.time + 1);
move(ans.x + dx[ans.dir], ans.y + dy[ans.dir], ans.dir, ans.step + 1, ans.time + 1);
}
return false;
}
int main()
{
// freopen("in.txt", "r", stdin);
int kase = 1;
while (~RII(a, b) && a)
{
if (kase != 1) puts("");
CLR(vis, false);
CLR(m, ‘#‘);
while (!q.empty()) q.pop();
FE(i, 1, a) FE(j, 1, b)
{
cin >> m[i][j];
if (m[i][j] == ‘S‘)
{
vis[i][j][0][0] = true;
tn = Node(i, j, 0, 0, 0);
q.push(tn);
}
else if (m[i][j] == ‘T‘)
ansx = i, ansy = j;
}
printf("Case #%d\n", kase++);
if (bfs(tn))
printf("minimum time = %d sec\n", tn.time);
else
puts("destination not reachable");
}
return 0;
}
原文:http://blog.csdn.net/wty__/article/details/21734991