【电子老鼠走迷宫】

本文介绍了一种使用广度优先搜索(BFS)算法解决迷宫寻路问题的方法。通过定义迷宫结构、起点与终点,利用队列实现节点扩展,最终找到从起点到终点的最短路径。
#include<iostream>
#include<queue>
using namespace std;

struct node{
    int x;
    int y;
    bool useful;
};
queue<node>q;
node start,target;

int used[15][15];
int step[15][15];
char maze[15][15];
int walk[4][2]={
    1,0,
    -1,0,
    0,1,
    0,-1,
};

node change(node now,int i)
{
    node next;
    next.useful=0;
    next.x=now.x+walk[i][0];
    next.y=now.y+walk[i][1];
    if(next.x>=0&&next.x<12&&next.y>=0&&next.y<12&&maze[next.x][next.y]=='.')
        next.useful=1;
    return next;
}

int bfs()
{
    node now,next;
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        for(int i=0;i<4;i++)
        {
            next=change(now,i);
            if(next.useful&&!used[next.x][next.y])
            {
                used[next.x][next.y]=1;
                step[next.x][next.y]=step[now.x][now.y]+1;
                if(next.x==target.x&&next.y==target.y)
                    return step[next.x][next.y];
                else
                    q.push(next);
            }
        }
    }
    return -1;
}

int main()
{
    int sx,sy,tx,ty;
    cin>>sx>>sy>>tx>>ty;
    start.x=sx-1;
    start.y=sy-1;
    target.x=tx-1;
    target.y=ty-1;
    for(int i=0;i<12;i++)
        for(int j=0;j<12;j++)
            cin>>maze[i][j];
    q.push(start);
    cout<<bfs()<<endl;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值