bfs:迷宫问题

从迷宫开始的s点走到t点,其中*代表墙壁,.代表平地。

#include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <vector>
#include <map>
#include <queue>
using namespace std;
const int maxn = 100;
struct Node{
    int x,y;
    int step;
};
Node start,end,temp;
int n,m;
char maze[maxn][maxn];
bool flag[maxn][maxn];
int mx[4]={0,0,1,-1};
int my[4]={1,-1,0,0};
bool Is_push(int x,int y)
{
    if(x>=n||x<0||y>=m||y<0) return false;
    if(flag[x][y] == true) return false;
    if(maze[x][y] == '*') return false;
    return true;
}
void bfs()
{
    int i;
    queue<Node>q;
    q.push(start);
    flag[start.x][start.y] = true;
    while(!q.empty())
    {
        temp = q.front();
        if(temp.x == end.x&&temp.y == end.y)
            return;
        int layer = temp.step;
        q.pop();
        for(i=0;i<4;i++)
        {
           int newx = temp.x+mx[i];
           int newy = temp.y+my[i];
           if(Is_push(newx,newy))
           {
               Node n;
               n.x = newx;
               n.y = newy;
               n.step = layer+1;
               q.push(n);
               flag[newx][newy] = true;
           }
        }
    }
}
int main()
{
    cin>>n>>m;
    int i,j;
    for(i = 0;i < n;i++)
    {
        getchar();
        for(j = 0;j < m; j++)
        {
            maze[i][j] = getchar();
        }
    }
    cin>>start.x>>start.y>>end.x>>end.y;
    start.step = 0;
    bfs();
    cout<<temp.step<<endl;
}

测试案例:
5 5

...
.S.
.**.
…T

输出:11

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值