题目链接:http://icpc.njust.edu.cn/Problem/Hdu/1253/
其实就是二维扩展到三维了,增加了搜索方向,其他的没什么不同。
代码如下:
1 #include<bits/stdc++.h> 2 using namespace std; 3 typedef unsigned int ui; 4 typedef long long ll; 5 typedef unsigned long long ull; 6 #define pf printf 7 #define mem(a,b) memset(a,b,sizeof(a)) 8 #define prime1 1e9+7 9 #define prime2 1e9+9 10 #define pi 3.14159265 11 #define lson l,mid,rt<<1 12 #define rson mid+1,r,rt<<1|1 13 #define scand(x) scanf("%llf",&x) 14 #define f(i,a,b) for(int i=a;i<=b;i++) 15 #define scan(a) scanf("%d",&a) 16 #define dbg(args) cout<<#args<<":"<<args<<endl; 17 #define inf 0x3f3f3f3f 18 #define maxn 55 19 int a,b,c,t,k; 20 int dir[6][3]={{1,0,0},{-1,0,0},{0,1,0},{0,-1,0},{0,0,1},{0,0,-1}}; 21 int Map[maxn][maxn][maxn]; 22 bool vis[maxn][maxn][maxn]; 23 struct node{ 24 int x,y,z,step; 25 }; 26 node cur,nxt; 27 bool ok(node& q) 28 { 29 return q.x>=1&&q.x<=a&&q.y>=1&&q.y<=b&&q.z>=1&&q.z<=c&&Map[q.x][q.y][q.z]==0&&!vis[q.x][q.y][q.z]; 30 } 31 int bfs() 32 { 33 queue<node>q; 34 node st; 35 st.x=st.y=st.z=1; 36 st.step=0; 37 vis[1][1][1]=1; 38 q.push(st); 39 while(!q.empty()) 40 { 41 cur=q.front(); 42 q.pop(); 43 if(cur.x==a&&cur.y==b&&cur.z==c&&cur.step<=k) 44 { 45 return cur.step; 46 } 47 f(i,0,5) 48 { 49 nxt=cur; 50 nxt.x+=dir[i][0]; 51 nxt.y+=dir[i][1]; 52 nxt.z+=dir[i][2]; 53 nxt.step++; 54 if(!ok(nxt))continue; 55 vis[nxt.x][nxt.y][nxt.z]=1; 56 // cout<<nxt.step<<" x:"<<nxt.x<<" y:"<<nxt.y<<" z:"<<nxt.z<<endl; 57 q.push(nxt); 58 } 59 } 60 return -1; 61 } 62 int main() 63 { 64 //freopen("input.txt","r",stdin); 65 //freopen("output.txt","w",stdout); 66 std::ios::sync_with_stdio(false); 67 scan(t); 68 while(t--) 69 { 70 scanf("%d%d%d%d",&a,&b,&c,&k); 71 f(i,1,a) 72 f(j,1,b) 73 f(k,1,c) 74 { 75 scan(Map[i][j][k]); 76 } 77 mem(vis,false); 78 pf("%d ",bfs()); 79 } 80 }