hdu 1240 Asteroids!
1.三维的BFS(语文太差好久才看懂)
2.我发现起点到终点的步数可以直接算出
|start.x-end.x|+|start.y-end.y|+|start.z-end.z|
只要判断能否走到终点
3.每次走过新的点都要记录已经走过
4.记得清空队列
5.要额外判断起点和终点相同的情况,用BFS会 no route。
#include<bits/stdc++.h>
using namespace std;
char room[10][10][10];
#define CHECK(x, y, z) (x<Hx && x>=0 && y<Hy && y>=0 && z<Hz && z>=0)
int dir[6][3]{{-1,0,0},{0,-1,0},{1,0,0},{0,1,0},{0,0,1},{0,0,-1}};
int Hx, Hy, Hz;
int N, num;// num记录步长
char c;
struct node{
int x, y, z;
};
bool BFS(int dx, int dy ,int dz, int *start, int *end){
num = 0;
node star, next;
queue <node> q;
while(!q.empty()) q.pop();
star.x = dx; star.y = dy; star.z = dz;
q.push(star);
while(!q.empty()){
star = q.front();
q.pop();
for(int i=0; i<6; ++i){
next.x = star.x + dir[i][0];
next.y = star.y + dir[i][1];
next.z = star.z + dir[i][2];
if(next.x == end[0] && next.y == end[1] && next.z == end[2]){
num = abs(next.x - start[0])+abs(next.y - start[1])+abs(next.z - start[2]);
return 1;
}
if(CHECK(next.x, next.y, next.z) && room[next.x][next.y][next.z] == 'O'){
room[next.x][next.y][next.z] = 'X';
q.push(next);
}
}
}
return 0;
}
int main(){
string s;
int start[3], end[3];
while(cin >> s >> N){
Hx = N; Hy = N; Hz = N;
for(int Z=0; Z<Hz; ++Z)
for(int Y=0; Y<Hy; ++Y)
for(int X=0; X<Hx ;++X)
cin >> room[X][Y][Z];
for(int i=0; i<3; ++i) cin >> start[i];
for(int i=0; i<3; ++i) cin >> end[i];
cin >> s;
bool f = 1;
for(int i=0; i<3; ++i)
if(start[i] != end[i]) f=0;
if(f) cout << N << ' ' << '0' << endl;
else if(BFS(start[0], start[1], start[2], start, end))
cout << N << ' ' << num << endl;
else cout << "NO ROUTE" << endl;
}
}
查看12道真题和解析