• 白皮书P34-迷宫的最短路径


    题目描述:

     样例:

    题解:

      这道题是典型的BFS题型,记录下一跳所有方向的数量,选择是进入下一步还是原地踏步,来进行步数的更新。当然,也可以开一个数组,利用前驱+1来记录每一个坐标到出发点点的最短距离。

      除此之外,开一个数组不断记录前驱,可以找到终点到起点的路径。

    代码:

    #include <iostream>
    #include <queue>
    #include <cstdio>
    #include <algorithm>
    
    using namespace std;
    int const N = 105;
    char mp[N][N];
    
    int minstep = 10005;
    int tt[N];
    
    struct Dian{
        int x,y;
    };
    
    queue<Dian> q;
    
    Dian d[N][N];
    
    Dian start;
    void bfs(int step){
        Dian s;
    
        if(!q.empty()){
            s = q.front();
            q.pop();
        }else{
            return;
        }
    
        if(mp[s.x][s.y] == 'G'){
            if(step < minstep){
                minstep = step;
            }
            return;
        }
        mp[s.x][s.y] = '#';
        Dian tmp;
        if(mp[s.x-1][s.y] == '.' || mp[s.x-1][s.y] == 'G'){
            tmp.x = s.x-1;
            tmp.y = s.y;
            d[tmp.x][tmp.y] = s;
            q.push(tmp);
            tt[step+1]++;
        }
        if(mp[s.x][s.y-1] == '.' || mp[s.x][s.y-1] == 'G'){
            tmp.x = s.x;
            tmp.y = s.y-1;
            d[tmp.x][tmp.y] = s;
            q.push(tmp);
            tt[step+1]++;
        }
        if(mp[s.x+1][s.y] == '.' || mp[s.x+1][s.y] == 'G'){
            tmp.x = s.x+1;
            tmp.y = s.y;
            d[tmp.x][tmp.y] = s;
            q.push(tmp);
            tt[step+1]++;
        }
        if(mp[s.x][s.y+1] == '.' || mp[s.x][s.y+1] == 'G'){
            tmp.x = s.x;
            tmp.y = s.y+1;
            d[tmp.x][tmp.y] = s;
            q.push(tmp);
            tt[step+1]++;
        }
        tt[step]--;
        if(tt[step] <= 0){
            bfs(step+1);
        }else{
            bfs(step);
        }
    }
    
    void showit(int x,int y){
        if(x == start.x && y == start.y){
            return;
        }
        Dian tmp = d[x][y];
    
        showit(tmp.x,tmp.y);
        cout << "(" << x << "," << y << ")" << endl;
    
    }
    
    
    int main() {
        int n,m;
        int endx,endy;
        cin >> n >> m;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                cin >> mp[i][j];
                if(mp[i][j] == 'S'){
                    start.x = i;
                    start.y = j;
                }
                if(mp[i][j] == 'G'){
                    endx = i;
                    endy = j;
                }
            }
        }
        q.push(start);
        bfs(0);
        cout << minstep << endl;
        showit(endx,endy);
        return 0;
    }
  • 相关阅读:
    Could not load file or assembly 'System.Core, Version=2.0.5.0
    r 数据分组处理
    r函数知识总结
    R-Sys.time计算程序运行时间
    R语言包_dplyr_1
    R语言系列:生成数据
    R语言-分组统计
    导数——平均变化率与瞬时变化率
    梯度下降法
    梯度
  • 原文地址:https://www.cnblogs.com/doubest/p/11888732.html
Copyright © 2020-2023  润新知