BFS---HDU1240 Asteroids!

BFS—HDU1240 Asteroids!

可以看成是迷宫问题 ,’O’ 可走 ‘X’不可通过。需注意:
1.START&&END 都是’X’
2.START&&END 输入时顺序是Z,Y,X 即先输入 Slice ,再输入Column,Row
简单BFS,在遍历之后将MAP[i][j][k]标记成FALSE,可就地标记已遍历状态,节省空间。记得初始化。
!!输入中无用字符的处理:
START N :scanf(“START %d\n”,&N);
END 直接 char a[5]; cin.getline(a,4);
回车 cin.get();
cin、getline、get的用法详解

#include
#include
#include
using namespace std;
struct reco {
    int x;
    int y;
    int z;
    int step;
};
int map[11][11][11];
int dir[6][3] = { {-1,0,0}, {1,0,0}, {0,-1,0},{0,1,0},{0,0,-1},{0,0,1} };
reco st,en;
int bfs() {
    queue que;
    que.push(st);
    int i,xi,yi,zi,stepi;
    reco fir, tem;
    while (que.empty() == 0) {
        fir = que.front();
        que.pop();
        if (fir.x == en.x&&fir.y == en.y&&fir.z == en.z)
            return fir.step;
        tem = fir;
        for (i = 0; i < 6; i++) {
            xi = fir.x + dir[i][0];
            yi = fir.y + dir[i][1];
            zi = fir.z + dir[i][2];
            if (map[xi][yi][zi] == 1||(xi==en.x&&yi==en.y&&zi==en.z)) {
                tem.x = xi;
                tem.y = yi;
                tem.z = zi;
                tem.step = fir.step + 1;
                que.push(tem);
                map[xi][yi][zi] = -1;
            }
        }
    }
    return -1;
}
int main() {
    int N;
    int i, j,k;
    char te;
    int a, b, c;
    while (scanf("START %d\n", &N) != EOF) {
        for (i = 0; i < N; i++)
            for (j = 0; j < N; j++)
                for (k = 0; k < N; k++)
                    map[i][j][k] = -1;
        for (i = 0; i < N; i++)
            for (j = 0; j < N; j++) {
                for (k = 0; k < N; k++) {
                    scanf("%c", &te);
                    if (te == 'O')
                        map[i][j][k] = 1;
                }
                cin.get();
            }
        cin >> a >> b >> c;
        st.x = c;
        st.y = a;
        st.z = b;
        st.step = 0;
        cin >> a >> b >> c;
        en.x = c;
        en.y = a;
        en.z = b;
        char as[5];
        cin.get();
        cin.getline(as, 4);
        int out = bfs();
        if (out != -1)
            cout << N << " " << out << endl;
        else cout << "NO ROUTE"<

你可能感兴趣的:(ACM,ACM/BFS)