bfs(c++

#include<iostream>
using namespace std;

struct note
{
    int x, y;//坐标
    int n;//步数
};

int main(void)
{
    struct note que[2501];//队列
    int a[51][51] = { 0 }, book[51][51] = { 0 };//book用来记录走过的点
    int next[4][2] = { {0,1},
                        {1,0},
                        {0,-1},
                        {-1,0} };
    int n, m, startx, starty, p, q, tx, ty, flag;//flag=0代表没到终点
    cin >> n >> m;//迷宫大小
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            cin >> a[i][j];
    cin >> startx >> starty >> p >> q;//起点和终点
    //队列初始化
    int head=1, tail=1;
    que[tail].x = startx;
    que[tail].y = starty;
    que[tail].n = 0;//走了0步
    tail++;
    book[startx][starty] = 1;
    flag = 0;
    while (head < tail)//队列不为空,循环
    {
        for (int k = 0; k <= 3; k++)//枚举顺时针方向上的下一步
        {
            //txty代表下一个点
            tx = que[head].x + next[k][0];
            ty = que[head].y + next[k][1];
            if (tx<1 || tx>n || ty<1 || ty>m)//越界
                continue;
            //这个点没有障碍物且没走过
            if (a[tx][ty] == 0 && book[tx][ty] == 0)
            {
                book[tx][ty] = 1;//走了
                //插入队列
                que[tail].x = tx;
                que[tail].y = ty;
                que[tail].n = que[head].n + 1;//head所拥有的步数+1
                tail++;
            }
            if (tx == p && ty == q)
            {
                flag = 1;
                break;//退出枚举
            }
        //如果没有到达终点
        //则要扩展完所有情况才能退出枚举
        //并且循环时head不会加1
        }
        if (flag == 1)
            break;//退出while
        head++;
    }
    cout << que[tail - 1].n;
    return 0;
}

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值