BFS 基础

做一道题复习一下BFS迷宫=

http://hncu.acmclub.com/index.php?app=problem_title&id=111&problem_id=1102
题目描述
小明置身于一个迷宫,请你帮小明找出从起点到终点的最短路程。
小明只能向上下左右四个方向移动。
输入格式
输入包含多组测试数据。输入的第一行是一个整数T,表示有T组测试数据。
每组输入的第一行是两个整数N和M(1<=N,M<=100)。
接下来N行,每行输入M个字符,每个字符表示迷宫中的一个小方格。
字符的含义如下:
‘S’:起点
‘E’:终点
‘-’:空地,可以通过
‘#’:障碍,无法通过
输入数据保证有且仅有一个起点和终点。
输出
对于每组输入,输出从起点到终点的最短路程,如果不存在从起点到终点的路,则输出-1。

样例输入

1
5 5
S-###
-----
##---
E#---
---##

下面的代码不仅得到了该题的解,还打印出了最短路径。
用一个队列实现BFS,每一个节点只有一个前驱

样例输出
9

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

const int maxn = 100+5;
char map[maxn][maxn];
int  vis[maxn][maxn];
int  dir[4][2]={1,0,-1,0,0,1,0,-1};
int ans,n,m,dx,dy,sx,sy;


struct node {
    int x;
    int y;
    int step;
};

node init;
node f[maxn][maxn];

int judge(int x,int y){
    if(x<0 || x>=n || y<0 || y>=n)
        return 1;
    if(vis[x][y] == 1 || map[x][y] == '#')
        return 1;
    return 0; 
}

void print_road(node u){
    node t = u;
    stack s;
    while(t.x!=sx || t.y!=sy){
        s.push(t);
        t = f[t.x][t.y];
    }
    printf("(%d,%d)->",init.x,init.y);
    while(!s.empty()){
        node p = s.top(); s.pop();
        if(s.size()==0){
            printf("(%d,%d)\n",p.x,p.y);
        }
        else{
            printf("(%d,%d)->",p.x,p.y);
        }
    }
}

void bfs(){
    queue q;
    node next;
    init.x = sx;
    init.y = sy;
    init.step = 0;
    vis[sx][sy] = 1;
    q.push(init);
    while(!q.empty()){
        node tmp = q.front();
        q.pop();
        if(map[tmp.x][tmp.y]=='E'){
            print_road(tmp);
            ans = tmp.step;
            return;
        }
        for(int i=0;i<4;i++){
            next.x = tmp.x+dir[i][0];
            next.y = tmp.y+dir[i][1];
            if(judge(next.x,next.y)) continue;
            next.step = tmp.step+1;
            vis[next.x][next.y] = 1;
            f[next.x][next.y] = tmp;
            q.push(next);
        }
    }
    ans = -1;
}

int main(){
    int T;
    cin>>T;
    while(T--){
        memset(vis,0,sizeof(vis));
        cin>>n>>m;
        for(int i=0;iscanf("%s",map[i]);
        for(int i=0;ifor(int j=0;jif(map[i][j]=='S'){
                    sx = i;sy = j;
                }
            }
        }
        bfs();
        printf("%d\n",ans);
    }
    return 0;
} 

你可能感兴趣的:(算法,bfs)