A. 走迷宫1

走迷宫是很有趣的一种游戏,能够锻炼人的记忆力和思维.现在,HK被困在一个迷宫里面了,请你帮助他找到一条最短的路径,能够让他走出迷宫.
迷宫使用一个N*M的矩阵来描述,矩阵中用'.'代表空格可以通行,用'*'代表障碍物,用'S'代表出发点,用'T'代表出口.例如下面的一个矩阵就描述了一个8*8的迷宫
.....T..
..*****.
......*.
*.***.*.
......*.
.****.*.
S..*....
........

每个字符代表1个格子,HK只能在格子间按上下左右的方向移动 

Input

每个输入文件只包含一组输入数据.
每组数据第一行是两个正整数N和M(N,M<=100).
接着是一个N*M的矩阵.

Output

如果HK能够走出迷宫,输出最少需要的步数;否则输出-1.

这道题是比较简单的广搜的题:

一层一层的把图遍历完,而不像是深搜,一下子走到图的最底端;

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
char a[110][110];
int vis[100][100];
int ax[5]={-1,0,1,0};
int ay[5]={0,-1,0,1};
int n,m;
struct Thing{
    int x,y;
    int step;
}end ,start,now;
int bfs(){
    queue <Thing> que;
    que.push(start);
    while(!que.empty()){
        now = que.front();
        if(now.x == end.x && now.y == end.y){
            return now.step;
        }
        que.pop();
        for(int i = 0; i < 4; i++){
           Thing temp;
           temp.x = now.x+ax[i];
           temp.y = now.y + ay[i];
           temp.step = now.step+1;
           if(temp.x >= 0 && temp.x < n && temp.y >= 0&& temp.y < m && a[temp.x][temp.y]!='*'&& !vis[temp.x][temp.y]){
              que.push(temp);
              vis[temp.x][temp.y]=1;
           }
        }
    }
    return -1;
}
int main(){

    while(cin >> n >> m){
        memset(a,0,sizeof(a));
        memset(vis,0,sizeof(vis));
        for(int i = 0;i < n; i++){
            cin >> a[i];

        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(a[i][j] == 'S'){
                    start.x = i;
                    start.y = j;
                    start.step = 0;
                    vis[i][j] = 1;
                }
                if(a[i][j] == 'T'){
                    end.x = i;
                    end.y = j;
                }
            }
        }
       cout << bfs() << endl;
    }
}
View Code
原文地址:https://www.cnblogs.com/zht0915/p/4941787.html