ACM 刷题之路 HDU 1240

这道题的是一个基于三维地图的广搜。需要注意的就是题目的输入格式。

题目输入:
START 1
O
0 0 0
0 0 0
END

START END 是固定输入每一组数据都会有这样的输入,START 后面的NUM是三维数组的长度,第二行这是三维数组的具体数值(“O”为可以该坐标可以通行,“X”为该点不可通行),下面两行则是开始坐标(三维)和目的坐标(三维)。

#include"stdio.h"
#include<queue>
#include<iostream>
using namespace std;
char map[20][20][20];
int vis[20][20][20];
int num;
struct node {
    int x;
    int y;
    int z;
    int step;
};
node Start;
node End;
int tx[] = { 1,-1,0,0,0,0 };
int ty[] = { 0,0,1,-1,0,0 };
int tz[] = { 0,0,0,0,1,-1 };
bool Cheak(node a)
{
    if (a.x < 0 || a.y < 0 || a.z < 0 ||
        a.x >= num || a.y >= num || a.z >= num
        || vis[a.x][a.y][a.z])
        return false;
    return true;
}
int bfs(node a)
{
    queue<node> q;
    q.push(a);
    a.step = 0;
    map[Start.x][Start.y][Start.z] = 'X';
    while (!q.empty())
    {
        node now, next;
        now = q.front();
        q.pop();
        if (now.x == End.x&&now.y == End.y&&now.z == End.z)
            return now.step;
        for (int i = 0; i < 6; i++)
        {
            next.x = now.x + tx[i];
            next.y = now.y + ty[i];
            next.z = now.z + tz[i];
            if (Cheak(next)) {
                next.step = now.step + 1;
                vis[next.x][next.y][next.z] = 1;
                q.push(next);
            }
        }
    }
    return -1;
}
int main()
{
    char str[10];
    while (~scanf("%s%d", str, &num))
    {
        for (int i = 0; i < num; i++)
        {
            for (int j = 0; j < num; j++)
            {
                scanf("%s", map[i][j]);
                for (int k = 0; k < num; k++)
                {
                    if (map[i][j][k] == 'O') vis[k][j][i] = 0;
                    else vis[k][j][i] = 1;
                }
            }
        }
        scanf("%d%d%d%d%d%d", &Start.x, &Start.y,
            &Start.z, &End.x, &End.y, &End.z);
        scanf("%s", str);
        int ans = bfs(Start);
        if (ans!=-1) printf("%d %d\n",num,ans);
        else printf("NO ROUTE\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34333801/article/details/80351875