• Dungeon Master


    给定一个多层的地牢(多维数组),'.'表示空白格, '#'表示障碍。给定一个起点和终点,可以在空白格移动,可以向上移动,向下移动,向左移动和向右移动,问到达终点的最短路径。

    思路:BFS

    #include<iostream>
    #include<queue>
    
    using namespace std;
    
    typedef struct pos{
      int x;
      int y;
      int z;
    }Pos;
    
    const int INF = 1000000;
    int L, R, C;
    int sx, sy, sz;
    int fx, fy, fz;
    char maze[40][40][40];
    int d[40][40][40];
    int dx[6] = {1, -1, 0, 0, 0, 0}, dy[6] = {0, 0, 0, 0, 1, -1}, dz[6] = {0, 0, -1, 1, 0, 0};
    
    void bfs(int x, int y, int z){
      Pos p;
      p.x = x;
      p.y = y;
      p.z = z;
      queue<Pos> q;
      q.push(p);
      d[x][y][z] = 0;
    
      while( !q.empty() ){
        Pos t = q.front(); q.pop();
    
        for(int i=0; i<6; i++){
          int nx = t.x + dx[i];
          int ny = t.y + dy[i];
          int nz = t.z + dz[i];
    
          if(nx >= 0 && nx < L && ny >= 0 && ny < R && nz >= 0 && nz < C && d[nx][ny][nz] == INF && maze[nx][ny][nz] != '#'){
            Pos rel;
            rel.x = nx;
            rel.y = ny;
            rel.z = nz;
            q.push(rel);
            d[nx][ny][nz] = d[t.x][t.y][t.z] + 1;
          }
        }
    
      }
    }
    
    int main(){
      ios::sync_with_stdio(false);
    
      while(cin >> L >> R >> C){
        if(L==0 && R==0 && C==0)
          break;
    
        for(int i=0; i<L; i++){
          for(int j=0; j<R; j++){
            for(int k=0; k<C; k++){
              d[i][j][k] = INF;
              cin >> maze[i][j][k];
              if(maze[i][j][k] == 'S'){
                sx = i;
                sy = j;
                sz = k;
              }
              if(maze[i][j][k] == 'E'){
                fx = i;
                fy = j;
                fz = k;
              }
            }
          }
        }
    
        bfs(sx, sy, sz);
        if(d[fx][fy][fz] != INF)
          cout << "Escaped in " << d[fx][fy][fz] << " minute(s)." << endl;
        else
          cout << "Trapped!" << endl;
      }
    
    
      return 0;
    }
  • 相关阅读:
    C# 多态性
    C# FileStream类
    C# File文件类
    加快访问GitHub的速度
    Git-修改.gitignore后使其配置生效的方法总结
    ES6 解构赋值
    avue表单数据请求
    uniapp canvas组件复用
    uniappH5 fly.js Golang 解决跨域问题
    java bug记录
  • 原文地址:https://www.cnblogs.com/ssNiper/p/11263191.html
Copyright © 2020-2023  润新知