The Monocycle UVA - 10047 bfs

#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 30;
const int dx[4] = { -1, 0, 1, 0 };
const int dy[4] = { 0, -1, 0, 1 };
int n, m;
int sr, sc, er, ec;
char g[N][N];
int t[N][N][4][5];
//t[r][c][dir][col]记录到达(r,c)处且方向为dir,底面颜色为col的最短时间
struct node
{
	int r, c, dir, col;//0代表绿色
};
int bfs()
{
	queue<node> que;
	while (!que.empty()) 
		que.pop();
	memset(t, -1, sizeof(t));
	que.push({sr, sc, 0, 0});
	while (!que.empty())
	{
		node tmp = que.front();
		int r = tmp.r;
		int c = tmp.c;
		int dir = tmp.dir;
		int col = tmp.col;
		que.pop();
		if (tmp.r == er && tmp.c == ec && tmp.col == 0)
			return 1 + t[tmp.r][tmp.c][tmp.dir][tmp.col];
		//直走
		int x = r + dx[dir];
		int y = c + dy[dir];
		if (x >= 0 && x < n && y >= 0 && y < m && '#' != g[x][y])
		{
			int nextCol = (col + 1) % 5;
			if (t[x][y][dir][nextCol] == -1)
			{
				t[x][y][dir][nextCol] = t[r][c][dir][col] + 1;
				que.push({x, y, dir, nextCol});
			}
		}
		//左右转
		int nextDir = (dir + 1) % 4;
		if (t[r][c][nextDir][col] == -1)
		{
			t[r][c][nextDir][col] = t[r][c][dir][col] + 1;
			que.push({r, c, nextDir, col});
		}
		nextDir = ((dir - 1) % 4 + 4) % 4;
		if (t[r][c][nextDir][col] == -1)
		{
			t[r][c][nextDir][col] = t[r][c][dir][col] + 1;
			que.push({r, c, nextDir, col} );
		}
	}
	return -1;
}
int main()
{
	int kase = 0;
	while (scanf("%d%d", &n, &m) == 2 && (n + m))
	{
		if (kase != 0)
			printf("\n");
		for (int i = 0; i < n; ++i)
			scanf("%s", g[i]);
		for (int i = 0; i < n; ++i)
			for (int j = 0; j < m; ++j)
				if ('S' == g[i][j])
					sr = i, sc = j;
				else if ('T' == g[i][j])
					er = i, ec = j;
		int ans = bfs();
		printf("Case #%d\n", ++kase);
		if (-1 != ans)
			printf("minimum time = %d sec\n", ans);
		else
			printf("destination not reachable\n");
	}
	return 0;
}
上一篇:UVA 156 Ananagrams STL应用


下一篇:Uva 11059 最大乘积