标签:bfs
1 10 *........X 1 3 *#X 3 20 #################### #XY.gBr.*.Rb.G.GG.y# #################### 0 0
Escape possible in 9 steps. The poor student is trapped! Escape possible in 45 steps.
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, m, t;
char map[100][100];
bool f[1029][100][100];
int dir[] = {0, 1, 0, -1, 0};
int sum[100];
struct node {
int x, y;
int temp;
__int64 w;
};
int bfs(node x)
{
queue<node>q;
q.push(x);
node a, b;
while (!q.empty()) {
a = q.front(); q.pop();
for (int i = 0; i < 4; i++) {
b = a;
b.x += dir[i];
b.y += dir[i + 1];
if (b.x < 0 || b.x >= n || b.y < 0 || b.y >= m)continue;
if (map[b.x][b.y] == '#')continue;
// if (b.temp >= t)return -1;
if (map[b.x][b.y] == 'b' || map[b.x][b.y] =='y' || map[b.x][b.y] == 'r' || map[b.x][b.y] == 'g') {
b.w|=(1<<(sum[map[b.x][b.y] - 'a']));
}
if (map[b.x][b.y] == 'B' || map[b.x][b.y] =='Y' || map[b.x][b.y] == 'R' || map[b.x][b.y] == 'G') {
if (!(b.w & (1<<sum[map[b.x][b.y] - 'A'])))continue;
}
if (f[b.w][b.x][b.y] != 0)continue;
b.temp++;
f[b.w][b.x][b.y] = true;
if (map[b.x][b.y] == 'X') {
// if (b.temp >= t)return -1;
return b.temp;
}
q.push(b);
}
}
return -1;
}
int main()
{
node a;
sum['B'-'A']=0,sum['Y'-'A']=1,sum['R'-'A']=2,sum['G'-'A']=3;
while (cin >> n >> m) {
if(n==m&&m==0)break;
memset(f, 0 , sizeof(f));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
cin >> map[i][j];
if (map[i][j] == '*') {
a.x = i;
a.y = j;
a.w = 0;
a.temp = 0;
}
}
int c = bfs(a);
if (c != -1)
cout << "Escape possible in " << c << " steps." << endl;
else
cout << "The poor student is trapped!" << endl;
//cout << bfs(a) << endl;
}
return 0;
}
标签:bfs
原文地址:http://blog.csdn.net/zhangweiacm/article/details/37913881