UVA10047 The Monocycle

微微发亮的传送门

不愧为佳哥啊,出的每一道水题都是超有水平的水题,非常好……这道题我们在搜索的时候要增加一个限制条件,方向和颜色,也就是说我们需要用四维数组来维护这些关系,那么我们要怎么判别呢?当然不能像是正常广搜一样进行四方向扩展,应该保证的是左转右转和前进,分这三种状态扩展,转一百八十度这种东西可以通过两个转弯来实现,为啥这么扩展呢?因为单纯的转弯也是要耗费时间的。70+行的广搜……

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int INF = 0x7fffffff;
const int N = 30;
char s[N][N];
int sx, sy, tx, ty, m, n, cnt, ans;
bool vis[N][N][5][4];
const int dir[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
struct node{
	int x, y, col, d, t;
	node(int x, int y, int col, int d, int t) : x(x), y(y), col(col), d(d), t(t){}
};
queue<node> Q;
void init(){
	memset(vis, 0, sizeof(vis));
	while(!Q.empty()) Q.pop();
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++){
			if (s[i][j] == 'S'){sx = i; sy = j;}
			if (s[i][j] == 'T'){tx = i; ty = j;}
		}
	cnt = 0;
	ans = INF;
	Q.push(node(sx, sy, 0, 0, 0));
	vis[sx][sy][0][0] = 1;
}
bool inMap(int x, int y){
	return x >= 0 && x < n && y >= 0 && y < m;
}
void bfs(){
	while(!Q.empty()){
		node u = Q.front();
		int x = u.x, y = u.y, col = u.col, d = u.d, t = u.t;
		if (x == tx && y == ty && col == 0){
			cnt += 1;
			ans = min(ans, t);
		}
		if (cnt >= 4) break;
		Q.pop();
		if (!vis[x][y][col][(d + 5) % 4]){
			vis[x][y][col][(d + 5) % 4] = 1;
			Q.push(node(x, y, col, (d + 5) % 4, t + 1));
		}
		if (!vis[x][y][col][(d + 3) % 4]){
			vis[x][y][col][(d + 3) % 4] = 1;
			Q.push(node(x, y, col, (d + 3) % 4, t + 1));
		}
		int xx = x + dir[d][0];
		int yy = y + dir[d][1];
		if (!inMap(xx, yy) || s[xx][yy] == '#' || vis[xx][yy][(col + 1) % 5][d]) continue;
		vis[xx][yy][(col + 1) % 5][d] = 1;
		Q.push(node(xx, yy, (col + 1) % 5, d, t + 1));
	}
}
int main(){
	int p = 1;
	while(~scanf("%d%d", &n, &m) && (n + m)){
		if (p != 1) puts("");
		printf("Case #%d\n", p++);
		for (int i = 0; i < n; i++)
			scanf("%s", s[i]);
		init(); bfs();
		if (ans == INF)
			printf("destination not reachable\n");
		else
			printf("minimum time = %d sec\n", ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值