P2360 地下城主 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
一道广搜题
#include<bits/stdc++.h> using namespace std; const int dx[]={0,0,0,0,1,-1};//偏移数组,最后两个是上楼或下楼 const int dy[]={1,-1,0,0,0,0}; const int dz[]={0,0,1,-1,0,0}; int l,r,c,posx1,posy1,posz1,posx2,posy2,posz2; struct node{ int x,y,z,t; }; queue<node> q;//定义结构体队列,标配 char a[55][55][55]; inline bool check(int x,int y,int z) { if(x>=1&&x<=l&&y>=1&&y<=r&&z>=1&&z<=c&&a[x][y][z]!='#') return true; return false; } inline int bfs(int x,int y,int z,int t) { a[x][y][z]='#'; q.push(node{x,y,z}); while(!q.empty()) { int xx=q.front().x; int yy=q.front().y; int zz=q.front().z; int tt=q.front().t; q.pop(); for(int i=0;i<6;i++) { int nx=xx+dx[i]; int ny=yy+dy[i]; int nz=zz+dz[i]; if(nx==posx2&&ny==posy2&&nz==posz2) return tt+1; if(check(nx,ny,nz)) { a[nx][ny][nz]='#'; q.push(node{nx,ny,nz,tt+1}); } } } return -1;//搜完了矩阵,队列都空了还没到终点就返回-1 } int main() { cin>>l>>r>>c; for(int i=1;i<=l;i++) { for(int j=1;j<=r;j++) { for(int k=1;k<=c;k++) { cin>>a[i][j][k]; if(a[i][j][k]=='S') { posx1=i; posy1=j; posz1=k;//起始层数,行与列 } if(a[i][j][k]=='E') { posx2=i; posy2=j; posz2=k;//终点层数行与列 } } } } int p=bfs(posx1,posy1,posz1,0);//可以开搜了 if(p!=-1) cout<<"Escaped in "<<p<<" minute(s)."<<endl; else cout<<"Trapped!"<<endl; return 0; }
 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号