bfs最短路径 迷宫问题

定义一个二维数组: 

int maze[5][5] = {

 0, 1, 0, 0, 0,

 0, 1, 0, 1, 0,

 0, 0, 0, 0, 0,

 0, 1, 1, 1, 0,

 0, 0, 0, 1, 0,

};

它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。 
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。 
Output
左上角到右下角的最短路径,格式如样例所示。 
Sample Input
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
Sample Output
(0, 0)
(1, 0)
(2, 0)
(2, 1)
(2, 2)
(2, 3)
(2, 4)
(3, 4)
(4, 4)

利用bfs,求最短路径,可以理解为把每一步的所有可能全部列举出来知道找到满足的条件为止,而且利用bfs找到的第一条路径,一定是最短的,其原理可以理解为不断扩大的圆直到把满足条件的点包括进去为止。
如果要求最短路径的长度,可以用队列进行操作将每一次扩展出来的路径进行储存,若是要求输出具体如何实现路径,就需要用数组进行模拟。

#include <iostream>
#include <cstdio>

using namespace std;

typedef struct node
{
    int x;
    int y;
    int step;//对应上一个通过扩展到该点的点在数组的位置。
}node;

node s[50];
void print(int head)//输出每一步路径
{
    if(s[head].step == -1)
        printf("(0, 0)\n");
    else
    {
        print(s[head].step);
        printf("(%d, %d)\n",s[head].x,s[head].y);
    }
}
int main()
{
    int dir[4][2] = {{1,0},{0,1},{-1,0},{0,-1}};//四个方向
    int v[10][10] = {0};//用来标记哪些点已经走过,减少时间
    int xx,yy,head = 0,tail = 0,flag = 0;//模拟队列首尾
    int map[5][5];//输入地图
    for(int i = 0; i < 5; i++)
        for(int j = 0; j < 5; j++)
            cin>>map[i][j];
    tail++;
    v[0][0] = 1;
    s[head].x = 0;
    s[head].y = 0;
    s[head].step = -1;
    while(head < tail)
    {
        for(int i = 0; i < 4; i++)
        {
            xx = s[head].x + dir[i][0];//进行移动,并储存路径上的点坐标
            yy = s[head].y + dir[i][1];
            if(xx >= 5||xx < 0||v[xx][yy] != 0||yy >= 5||yy < 0||map[xx][yy] ==1)
                continue;
            v[xx][yy] = 1;
            s[tail].x = xx;
            s[tail].y = yy;
            s[tail].step = head;
            tail++;
            if(xx == 4&&yy == 4)//找到出口
            {
                flag = 1;
                break;
            }
        }
        if(flag)
        {
            print(head);
            printf("(4, 4)\n");
            break;
        }
        head++;
    }
    return 0;
}

Cu1
发布了30 篇原创文章 · 获赞 2 · 访问量 957

猜你喜欢

转载自blog.csdn.net/CUCUC1/article/details/104948149
今日推荐