Loading

白皮书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;
}

 

 

 

posted @ 2019-11-19 13:33  Doubest  阅读(185)  评论(0编辑  收藏  举报