The Monocycle UVA - 10047 bfs

Posted qingyuyyyyy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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("
");
		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
", ++kase);
		if (-1 != ans)
			printf("minimum time = %d sec
", ans);
		else
			printf("destination not reachable
");
	}
	return 0;
}

以上是关于The Monocycle UVA - 10047 bfs的主要内容,如果未能解决你的问题,请参考以下文章

UVA 10047 - The Monocycle(BFS)

uva10047(未AC)

Undraw the Trees UVA - 10562

UVA 811 The Fortified Forest (凸包 + 状态压缩枚举)

UVA Mapping the Swaps

UVA10562-Undraw the Trees(递归)