“ Ctrl AC!一起 AC!”
题目:忘题戳这
分析:和普通的寻路一样,只要把地图的二维数组变成三维就可以
建议先做一下二维寻路再来写这题:参考博客某二维寻路题解
AC代码:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;
struct node {
int r, c, z, step;//队列存放的坐标,和步数
};
char map[35][35][35];//地图
int visit[35][35][35];//访问记录
int sr, sz, sc, r, c, z;//起点和地图大小
int dx[] = { 0,1,-1,0,0,0 };
int dy[] = { 1,0,0,-1,0,0 };
int dz[] = { 0,0,0,0,1,-1 };
int bfs() {
queue<node> q;
node first;
first.r = sr, first.c = sc, first.z = sz, first.step = 0;
q.push(first);
while (!q.empty()) {
node temp = q.front(); q.pop();
for (int i = 0; i < 6; i++) {//就是由四个方向变成了六个方向
int nowr = temp.r + dx[i];
int nowc = temp.c + dy[i];
int nowz = temp.z + dz[i];
int nowstep = temp.step + 1;
//三种剪枝
if (nowr<1 || nowr>r || nowc<1 || nowc>c || nowz<1 || nowz>z) continue;
if (map[nowz][nowr][nowc] == '#') continue;
if (visit[nowz][nowr][nowc]) continue;
if (map[nowz][nowr][nowc]=='E') {
return nowstep;
}
node next;
next.r = nowr, next.c = nowc, next.z = nowz, next.step = nowstep;
q.push(next);
visit[nowz][nowr][nowc] = 1;
}
}
return -1;
}
int main() {
while (cin >> z >> r >> c && z && r && c) {
memset(visit, 0, sizeof(visit));//初始化
memset(map, '\0', sizeof(map));
for (int i = 1; i <= z; i++) {
for (int j = 1; j <= r; j++) {
for (int k = 1; k <= c; k++) {
cin >> map[i][j][k];
if (map[i][j][k] == 'S') sz=i,sr=j,sc=k;//记录起点
}
}
}
int ans = bfs();
if (ans == -1) cout << "Trapped!" << endl;
else printf("Escaped in %d minute(s).\n", ans);
}
return 0;
}
感谢阅读!!!
“ Ctrl AC!一起 AC!”