题目:http://acm.hdu.edu.cn/showproblem.php?pid=1240
题意:空间 中的bfs。六个方向,O(大写的)可以走,X代表星星,不可以走。问你走几步可以走到指定位置。题目中有一句话是“Both the Starting Position and the Target Position will be in empty space.。但是它给的第二组数据很明显不是O。纠结。然后把对应的两点vis[][][]改成false才过。
想法:直接bfs。六个方向。这道题的输入直接把弄糊涂了。。。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
struct node{
int x,y,z;
int step;
};
node t,temp;
bool vis[110][110][110];
int n;
int a,b,c;
int d,e,f;
queue <node> s;
char str[10];
int ok(int i,int j,int k){
if(i>=0&&i<n&&j>=0&&j<n&&k>=0&&k<n) return 1;
else return 0;
}
int bfs(int i,int j,int k){
while(!s.empty()) s.pop();
t.x=i,t.y=j,t.z=k;
t.step=0;
s.push(t);
while(!s.empty()){
temp=s.front();
if(temp.x==d&&temp.y==e&&temp.z==f) return 1;
s.pop();
if(!vis[temp.x+1][temp.y][temp.z]&&ok(temp.x+1,temp.y,temp.z)){
vis[temp.x+1][temp.y][temp.z]=true;
t.x=temp.x+1;
t.y=temp.y;
t.z=temp.z;
t.step=temp.step+1;
s.push(t);
}
if(!vis[temp.x-1][temp.y][temp.z]&&ok(temp.x-1,temp.y,temp.z)){
vis[temp.x-1][temp.y][temp.z]=true;
t.x=temp.x-1;
t.y=temp.y;
t.z=temp.z;
t.step=temp.step+1;
s.push(t);
}
if(!vis[temp.x][temp.y-1][temp.z]&&ok(temp.x,temp.y-1,temp.z)){
vis[temp.x][temp.y-1][temp.z]=true;
t.x=temp.x;
t.y=temp.y-1;
t.z=temp.z;
t.step=temp.step+1;
s.push(t);
}
if(!vis[temp.x][temp.y+1][temp.z]&&ok(temp.x,temp.y+1,temp.z)){
vis[temp.x][temp.y+1][temp.z]=true;
t.x=temp.x;
t.y=temp.y+1;
t.z=temp.z;
t.step=temp.step+1;
s.push(t);
}
if(!vis[temp.x][temp.y][temp.z-1]&&ok(temp.x,temp.y,temp.z-1)){
vis[temp.x][temp.y][temp.z-1]=true;
t.x=temp.x;
t.y=temp.y;
t.z=temp.z-1;
t.step=temp.step+1;
s.push(t);
}
if(!vis[temp.x][temp.y][temp.z+1]&&ok(temp.x,temp.y,temp.z+1)){
vis[temp.x][temp.y][temp.z+1]=true;
t.x=temp.x;
t.y=temp.y;
t.z=temp.z+1;
t.step=temp.step+1;
s.push(t);
}
}
return 0;
}
int main(){
//freopen("123.txt","r",stdin);
while(scanf("%s",str)!=EOF){
scanf("%d",&n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%s",str);
for(int k=0;str[k];k++) {
if(str[k]=='O') vis[i][j][k]=false;
else vis[i][j][k]=true;
}
}
}
scanf("%d%d%d",&a,&b,&c);
scanf("%d%d%d",&d,&e,&f);
vis[a][b][c]=false;
vis[d][e][f]=false;
scanf("%s",str);
int ans=bfs(a,b,c);
if(ans)
printf("%d %d\n",n,temp.step);
else
printf("NO ROUTE\n");
}
return 0;
}
本文详细介绍了如何使用BFS算法解决HDOJ平台上的空间搜索问题,通过实例分析了从起点到目标点的最短路径计算方法,并解决了输入数据解析的困惑。
3084

被折叠的 条评论
为什么被折叠?



