您的位置:首页 > 其它

hdu2102 BFS

2016-04-01 17:22 106 查看
这是一道BFS的搜索题目,只是搜索范围变为了三维。定义数组visit[x][y][z]来标记空间位置,x表示楼层,y和z表示相应楼层的平面坐标。

#define _CRT_SECURE_NO_DEPRECATE
#include<iostream>
using namespace std;
#include<queue>
#define MAX_SIZE 12
int N, M, T;
char visit[2][MAX_SIZE][MAX_SIZE];
char map[2][MAX_SIZE][MAX_SIZE];
int dir[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
struct Point{
int x, y, z, step;
bool Isleg() {
if ( y<0 || y>N-1||z<0||z>M-1||map[x][y][z]=='*'||visit[x][y][z])
return false;
return true;
}
};
int BFS();
int main() {
int i,c,res;
scanf("%d", &c);
while(c--){
scanf("%d%d%d", &N, &M, &T);
for (i = 0; i <N; i++)
scanf("%s", map[0][i]);
for (i =0; i < N;i++)
scanf("%s",map[1][i]);
res = BFS();
if (res <= T)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
int BFS() {
Point next, pos;
int k,i,j;
for (i = 0; i < 2; i++) {
for (k = 0; k <N; k++)
for (j = 0; j <M; j++)
visit[i][k][j] = 0;
}
pos.x = 0, pos.y = 0,pos.z=0;     //入口位置
pos.step = 0;
queue<Point>Q;
Q.push(pos);                      //入口位置首先入队
visit[pos.x][pos.y][pos.z] = 1;   //入口位置标记为访问
while (!Q.empty()) {
pos = Q.front();
Q.pop();
if (map[pos.x][pos.y][pos.z] == 'P')
return  pos.step;
pos.step++;
if (map[pos.x][pos.y][pos.z] == '#') {
next = pos;
next.x = (next.x + 1) % 2;       //进入下一层
if (next.Isleg()) {
visit[next.x][next.y][next.z] = 1;
next.step--;         //时空传输不发费时间
Q.push(next);
}
}
else {
for (k = 0; k < 4; k++) {     //扫描四个方向
next = pos;
next.y += dir[k][0];
next.z += dir[k][1];
if (next.Isleg()) {
visit[next.x][next.y][next.z] = 1;
Q.push(next);
}
}
}
}
return INT_MAX;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: