簡單BFS,和二維的做法相同(需注意坐標)
題目大意:三維的空間裡,給出起點和終點,“O”表示能走,“X”表示不能走,計算最少的步數
#include <iostream> #include <stdio.h> #include <string.h> #include <queue> using namespace std; char map[11][11][11]; int v[11][11][11],d[6][3] = { {1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,-1},{0,0,1} }; int begin_x,begin_y,begin_z,end_x,end_y,end_z; int flag,n; struct node { int x,y,z; int step; }; void bfs() { queue <node> q; node s,temp; s.x = begin_x; s.y = begin_y; s.z = begin_z; s.step = 0; v[s.x][s.y][s.z] = 0; q.push(s); while(!q.empty()) { temp = q.front(); q.pop(); if(temp.x == end_x && temp.y == end_y && temp.z == end_z) { printf("%d %d\n",n,temp.step); flag = 1; return ; } for(int i = 0 ; i < 6 ; i ++) { s = temp; s.x += d[i][0]; s.y += d[i][1]; s.z += d[i][2]; if(s.x < 0 || s.x >= n || s.y < 0 || s.y >= n || s.z < 0 || s.z >= n || map[s.x][s.y][s.z] == 'X') continue; s.step ++; if(s.step < v[s.x][s.y][s.z]) { v[s.x][s.y][s.z] = s.step; q.push(s); } } } } int main() { //freopen("in.txt","r",stdin); char a[20]; int i,j; while(~scanf("%s%d",a,&n)) { for(i = 0 ; i < n ; i ++) for(j = 0 ; j < n ; j ++) scanf("%s",map[i][j]); scanf("%d%d%d",&begin_z,&begin_y,&begin_x); scanf("%d%d%d",&end_z,&end_y,&end_x); scanf("%s",a); memset(v,1,sizeof(v)); flag = 0; bfs(); if(!flag) printf("NO ROUTE\n"); } return 0; }