迷宫问题题

迷宫问题-广度优先搜索

题目信息

迷宫有一个入口,一个出口。一个人从入口走进迷宫,目标是找到出口。阴影部分和迷宫的外框为墙,每一步走一格,每格有四个可走的方向,探索顺序为地图方向:南(下)、东(右)、北(上)、西(左)。
在这里插入图片描述

输入

输入迷宫数组。第一行数据表示一个 n*n (n<=100)的迷宫;第二行开始的n行为迷宫数据。其中:0表示路,1表示墙,起点在左上角<1,1>的位置,终点在右下角 <n,n> 的位置。

输出

若有解,输出从入口到出口的一条路径,否则输出 there is no solution!

测试样例

测试样例1

4 4
0 0 1 0
0 1 0 1
0 0 0 0
0 1 0 0
<1,1> <2,1> <3,1> <3,2> <3,3> <4,3> <4,4> 

测试样例2

4 4
0 0 1 0
1 0 1 1
0 0 0 1
0 1 0 1
There is no solution!

解答

#include <cstring>
#include <iostream>

using namespace std;

bool map[105][105]; //地图
bool vis[105][105]; //判重
int dir[4][2] = {{-1, 0},
                 {1,  0},
                 {0,  -1},
                 {0,  1}};//四个方向
int N;

struct node
{
    int x, y; //坐标
    int c;   //上一点
} queue[105 * 105];

void print(int head)
{
    while (queue[head].c != -1)
    {
        print(queue[head].c);
        cout << "<" << queue[head].x + 1 << "," << queue[head].y + 1 << ">" << " ";
        return;
    }
    printf("<1,1> ");
}

int bfs(int x, int y)
{
    int head = 0, tail = 1;
    //队列中第一个便是左上角的点,它的坐标(0,0)。前导无
    queue[0].x = 0;
    queue[0].y = 0;
    queue[0].c = -1;

    struct node now;//取一个中间值点
    while (head < tail)
    {//如果头小于尾
        if (queue[head].x == N - 1 && queue[head].y == N - 1)
        {//终点判定点条件,如果走到了最后
            return head;
        }
        for (int i = 0; i < 4; i++)
        {//现在向0,1,2,3四个方向去走
            now.x = queue[head].x + dir[i][0];
            now.y = queue[head].y + dir[i][1];
            now.c = head;//找到了现在点的位置

            if (now.x >= 0 && now.x < N && now.y >= 0 && now.y < N)
            {//如果这个点符合在地图内
                if (!vis[now.x][now.y] && !map[now.x][now.y])
                {//如果没有遍历过,且地图中是(路0)
                    vis[now.x][now.y] = 1;//将其更改为遍历过
                    queue[tail] = now;//队尾增添当前元素
                    tail++;
                }
            }
        }
        head++;//四个方向遍历完了头增加一个
    }
    return 0;
}

int main()
{
    //freopen("/Users/zhj/Downloads/test.txt", "r", stdin);
    cin >> N >> N;
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {//先将点都输入到地图中
            cin >> map[i][j];
        }
    }
    memset(vis, 0, sizeof(vis));
    int head = bfs(0, 0);
    
    if (head == 0)
    {
        cout << "There is no solution!";
    }
    else
    {
        print(head);
    }
    cout << endl;
    return 0;
}
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhj12399

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值