这道题目,三维空间上的BFS,给你起点和终点,看能否找到一条路,O表示可以走,X表示不可以走!~
理解了题目,就可以用队列来实现BFS来求解。
下面的是AC 的代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
class data
{
public:
int xyz;
int count;
};
char map[11][11][11];
bool flag[11][11][11];
char str[10];
int xyz[6][3] = {0,0,1,0,0,-1,0,1,0,0,-1,0,1,0,0,-1,0,0}; //三维上的六个方向
int n;
int sx, sy, sz; //起点
int ex, ey, ez;<span style="white-space:pre"> </span> //终点
int BFS() //BFS
{
queue<data>Q;
while(!Q.empty())
Q.pop();
if(sx == ex && sy == ey && sz == ez && map[sx][sy][sz] == 'O' && map[ex][ey][ez] == 'O')
return 0;
data temp, te;
int x, y, z, temp1;
temp.xyz = sx * 100 + sy * 10 + sz;
temp.count = 0;
flag[sx][sy][sz] = true;
Q.push(temp);
while(!Q.empty())
{
temp = Q.front();
Q.pop();
for(int i = 0; i < 6; i++)
{
temp1 = temp.xyz;
x = temp1 / 100 + xyz[i][0];
temp1 %= 100;
y = temp1 / 10 + xyz[i][1];
temp1 %= 10;
z = temp1 + xyz[i][2];
if(x == ex && y == ey && z == ez)
return temp.count + 1;
if(x >= 0 && x < n && y >= 0 && y < n && z >= 0 && z < n && map[x][y][z] != 'X' && !flag[x][y][z])
{
te.xyz = x * 100 + y * 10 + z;
te.count = temp.count + 1;
Q.push(te);
flag[x][y][z] = true;
}
}
}
return -1;
}
int main()
{
// freopen("data.txt", "r", stdin);
int i, j, k;
while(scanf("%s%d", str, &n) != EOF) //输入的处理!比较麻烦
{
getchar();
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
for(k = 0; k < n; k++)
scanf("%c", &map[i][j][k]);
getchar();
}
}
scanf("%d%d%d", &sx, &sy, &sz);
scanf("%d%d%d", &ex, &ey, &ez);
getchar();
scanf("%s", str);
getchar();
memset(flag, false, sizeof(flag));
int ans = BFS();
if(ans < 0)
printf("NO ROUTE\n");
else
printf("%d %d\n", n, ans);
}
return 0;
}