利用BFS算法解决迷宫问题

#include<iostream>
#include<limits.h>
#include<queue>
#include<vector>
#define MAX_V_NUM 100  //顶点的最大个数
using namespace std;
struct Box
{
    int x;
    int y;
    int lastIndex;
    int index;
};

int main()
{
    vector<Box> vec;
    int size;
    int map[MAX_V_NUM][MAX_V_NUM] = { 0 };
    int visit[MAX_V_NUM][MAX_V_NUM] = { 0 };
    cin >> size;
    for (int i = 0; i < size + 2; i++)
        for (int j = 0; j < size + 2; j++)
            cin >> map[i][j];
    queue<Box> qu;
    Box start = { 1,1,-1,0};
    vec.push_back(start);
    qu.push(start);
    visit[1][1] = 1;
    while (!qu.empty())
    {
        Box temp = qu.front();
        if (temp.x == size && temp.y == size)break;
        qu.pop();
        if (map[temp.x + 1][temp.y] == 0&&visit[temp.x+1][temp.y]==0)
        {
            Box box = { temp.x + 1,temp.y,temp.index,vec.size() };
            qu.push(box);
            vec.push_back(box);
            visit[temp.x + 1][temp.y] = 1;
        }
        if (map[temp.x][temp.y+1] == 0 && visit[temp.x][temp.y+1] == 0)
        {
            Box box = { temp.x ,temp.y+1,temp.index,vec.size() };
            qu.push(box);
            vec.push_back(box);
            visit[temp.x][temp.y+1] = 1;
        }
        if (map[temp.x][temp.y -1] == 0 && visit[temp.x][temp.y -1] == 0)
        {
            Box box = { temp.x ,temp.y -1,temp.index,vec.size() };
            qu.push(box);
            vec.push_back(box);
            visit[temp.x][temp.y -1] = 1;
        }
    }
    if (qu.empty())
    {
        cout << "no path";
    }
    else
    {
        cout << "Find path"<<endl;
        int index[MAX_V_NUM] = { 0 };
        int i = 0;
        Box temp = qu.front();
        qu.pop();
        while (temp.lastIndex!=-1)
        {
            index[i++]=temp.index;
            temp = vec[temp.lastIndex];
        }
        cout << 1 << ' ' << 1 << endl;
        for (int j = i-1; j>=0; j--)
            cout << vec[index[j]].x << ' ' << vec[index[j]].y << endl;
    }
    return 0;
}

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值