题目大意:
一个立体空间, 输入三个数,L,R,C,代表有L个平面,R行,C列,.代表可以走,#代表不能走,S代表开始点,E代表结束点,问从S开始走,对每个位置,有六个走法,即空间的六个方向的走法(上下东南西北),一分钟可以走一个点,问从S走到E点,最少可以经过多少分钟,若不能到达,则输出Trapped!
使用BFS。队列用单链表形式(也可以用数组来表示,但要指定足够长的长度。也可以用vector等)
#include<iostream>
using namespace std;
char dungeon[30][30][30];
bool mark[30][30][30] = { false }; //用来标记某点是否被搜索过
int step[6][3] = { 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, -1 }; //6个方向,6步
int Start[3], End[3]; //S和E点的坐标
int L, R, C;
struct node{
int point[3];
node* pNext;
};
struct MyQueue{
node* front = NULL;
node* rear = NULL;
};
MyQueue* q = new MyQueue;
void del(int* retPnt)
{
if (q->front == NULL) return;
for (int i = 0; i < 3; ++i)
retPnt[i] = q->front->point[i];
node* temp = q->front;
q->front = q->front->pNext;
delete temp;
if (q->front == NULL) q->rear = NULL;
}
void insert(int* point)
{
node* Node = new node;
for (int i = 0; i < 3; ++i)
Node->point[i] = point[i];
Node->pNext = NULL;
if (q->front == NULL)
{
q->front = Node;
q->rear = Node;
}
else
{
q->rear->pNext = Node;
q->rear = Node;
}
}
void bfs(int* point)
{
if (point[0] == -1)
{
cout << "impossible";
return;
}
if (dungeon[point[0]][point[1]][point[2]] == 'E')
{
for (int i = 0; i < 3; ++i)
End[i] = point[i];
return;
}
int temp[3] = { 0 };
int pnt[3] = {-1,-1,-1};
mark[point[0]][point[1]][point[2]] == true; //表示该点已经被搜索过。
for (int i = 0; i < 6; ++i)
{
bool flag = true;
for (int j = 0; j < 3; ++j)
temp[j] = point[j] + step[i][j];
if (temp[0] < 0 || temp[0] >= L||temp[1]<0
||temp[1]>=R||temp[2]<0||temp[2]>=C)
flag = false;
if (flag == true && dungeon[temp[0]][temp[1]][temp[2]] != '#'
&& mark[temp[0]][temp[1]][temp[2]] == false)
insert(temp);
}
del(pnt);
bfs(pnt);
}
void main()
{
cin >> L >> R >> C;
for (int i = 0; i < L; ++i)
for (int j = 0; j < R; ++j)
for (int k = 0; k < C; ++k)
{
cin >> dungeon[i][j][k];
if (dungeon[i][j][k] == 'S') {
Start[0] = i; Start[1] = j; Start[2] = k;
}
}
bfs(Start);
int time = 0;
for (int i = 0; i < 3; ++i)
time += End[i] - Start[i];
cout << time+2;
}