宽度优先搜索——迷宫的最短路径

来源:互联网 发布:合肥工业大学网络选课 编辑:程序博客网 时间:2024/06/05 02:24

      迷宫的最短路径

  给定一个大小为M*N的迷宫,迷宫由通道和墙壁组成,每一步可以向邻接的上下左右四格的通道移动。请求出从起点到终点所需的最小步数。

#表示墙壁

'.'表示通道

S表示起点

G表示终点

#include <iostream>#include <utility>#include <queue>using namespace std;const int INF = 10000000;typedef pair<int, int> Point;int sx;//起点坐标int sy;int gx;//终点坐标int gy;//到各个位置的最短距离的数组int d[100][100];//4个方向移动的向量,对应相对于当前点的四个方向(1,0),(0,1),(-1,0),(0,1)int dx[4] = {1, 0, -1, 0};int dy[4] = {0, 1, 0, -1};//求从(sx, sy)到(gx, gy)的最短距离,无法到达则是INFint dfs(char a[10][11]){    int M = 10;    int N = 10;    //定义一个队列存储各状态    queue<Point> que;    //把所有位置都初始化为INF    for(int i = 0; i < M; ++i)    {        for(int j = 0; j < N; ++j)        {            d[i][j] = INF;        }    }    //将起始点加入队列并把距离设置为0    que.push(Point(sx, sy));    d[sx][sy] = 0;    //不断循环知道队列的长度为0    while(que.size())    {        //从队首取元素        Point p = que.front();        //删除队首元素,但不返回任何值        que.pop();        //如果所取状态已是终点,则结束搜索        if(p.first == gx && p.second == gy)        break;        //四个方向的循环        for(int k = 0; k < 4; ++k)        {            //移动之后的位置为(nx, ny)            int nx = p.first + dx[k];            int ny = p.second + dy[k];            //判断是否可以移动以及是否是已访问过(d[nx][ny] != INF为已访问过的)            if(0 <= nx && nx < M && 0 <= ny && ny < N && d[nx][ny] == INF && a[nx][ny] != '#')            {                //可以移动的话,则加入到队列,并且到该位置的距离确定为到p的距离 + 1                que.push(Point(nx, ny));                d[nx][ny] = d[p.first][p.second] + 1;            }        }    }    return d[gx][gy];}int main(){    //定义一个迷宫的字符串数组    char maze[10][11] = {                           {'#', 'S', '#', '#', '#', '#', '#', '#', '.', '#'},                           {'.', '.', '.', '.', '.', '.', '#', '.', '.', '#'},                           {'.', '#', '.', '#', '#', '.', '#', '#', '.', '#'},                           {'.', '#', '.', '.', '.', '.', '.', '.', '.', '.'},                           {'#', '#', '.', '#', '#', '.', '#', '#', '#', '#'},                           {'.', '.', '.', '.', '#', '.', '.', '.', '.', '#'},                           {'.', '#', '#', '#', '#', '#', '#', '#', '.', '#'},                           {'.', '.', '.', '.', '#', '.', '.', '.', '.', '.'},                           {'.', '#', '#', '#', '#', '.', '#', '#', '#', '.'},                           {'.', '.', '.', '.', '#', '.', '.', '.', 'G', '#'}                        };    cin >> sx;    cin >> sy;    cin >> gx;    cin >> gy;    int result = dfs(maze);    cout << result << endl;    return 0;}


 

原创粉丝点击