标签:
题目大意:有一个n*m的网格,网格上面有的地方有障碍物
现在有一个人,骑着独轮车,要求从一个地方到达另一个地方,骑独轮车时,只能直走,或者左拐,右拐,不能向后走
独轮车的轮子被分成了5部分,每部分都有对应的颜色,刚开始时是绿色向下,当经过一个格子时,颜色就会变换
问从起点出发到终点,到终点时独轮车的绿色颜色向下,需要多久
解题思路:暴力BFS
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define N 30
struct Node{
int x, y, dir, time, color;
}start;
int dir[4][2] = {{-1, 0}, {0, 1}, {0, -1}, {1, 0}};
int g[N][N], vis[N][N][5][4];
char str[N];
int end_x, end_y, n, m;
void init() {
for (int i = 0; i < n; i++) {
scanf("%s", str);
for (int j = 0; j < m; j++) {
if (str[j] == ‘#‘) {
g[i][j] = 1;
}
else {
g[i][j] = 0;
if (str[j] == ‘S‘) {
start.x = i;
start.y = j;
}
if (str[j] == ‘T‘) {
end_x = i;
end_y = j;
}
}
}
}
memset(vis, 0, sizeof(vis));
}
void solve() {
queue<Node> q;
start.color = 0;
start.time = 0;
start.dir = 0;
q.push(start);
vis[start.x][start.y][0][0] = 1;
while (!q.empty()) {
Node t = q.front();
q.pop();
if (t.x == end_x && t.y == end_y && t.color == 0) {
printf("minimum time = %d sec\n", t.time);
return ;
}
for (int i = 0; i < 4; i++) {
if (t.dir + i == 3)
continue;
Node tt;
tt.x = t.x;
tt.y = t.y;
tt.color = t.color;
tt.time = t.time + 1;
tt.dir = t.dir;
if(tt.dir == i) {
tt.x += dir[tt.dir][0];
tt.y += dir[tt.dir][1];
tt.color = (tt.color + 1) % 5;
if(tt.x < 0 || tt.x >= n || tt.y < 0 || tt.y >= m || g[tt.x][tt.y] || vis[tt.x][tt.y][tt.color][tt.dir])
continue;
vis[tt.x][tt.y][tt.color][tt.dir] = 1;
q.push(tt);
}
else {
tt.dir = i;
if(!vis[tt.x][tt.y][tt.color][tt.dir]) {
vis[tt.x][tt.y][tt.color][tt.dir] = 1;
q.push(tt);
}
}
}
}
printf("destination not reachable\n");
}
int main() {
int cas = 1;
int flag = 0;
while (scanf("%d%d", &n, &m) != EOF && n + m) {
if(flag)
printf("\n");
else
flag = 1;
init();
printf("Case #%d\n", cas++);
solve();
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
UVA - 10047 The Monocycle (BFS)
标签:
原文地址:http://blog.csdn.net/l123012013048/article/details/47055299