简单的迷宫

给定一个迷宫,问是否可以走出去,入口固定为左上角,出口为右下角,且只能上下左右直线移动。

#include<bits/stdc++.h>
#define inf -0x3f3f3f3f
#define maxsize 100
using namespace std;

bool bfs();
void init(int n,int m);


struct graph
{
    int x;
    int y;
};

int n,m;///迷宫的行数和列数

int g[maxsize][maxsize];
bool check[maxsize][maxsize];

int main()
{

    memset(g,inf,sizeof(g));
    cin>>n>>m;

    init(n,m);
    if(bfs()) cout<<"yes"<<endl;
    else    cout<<"no"<<endl;

    
    return 0;

}
void init(int n,int m)///初始化迷宫
{
    for(int i = 1;i <= n; i++)
        for(int j = 1;j <= m; j++)
            cin>>g[i][j];
}
bool bfs()
{
    queue<graph> q;
    graph v;
    v.x = v.y = 1;
    check[v.x][v.y] = true;

    q.push(v);

    while(!q.empty())
    {

        graph node = q.front();
        q.pop();
        if(node.x==n&&node.y==m)
            return true;

        if(g[node.x-1][node.y]>0&&(!check[node.x-1][node.y]))///上移
        {
            graph w;
            w.x = node.x-1;
            w.y = node.y;
            check[w.x][w.y] = true;
            q.push(w);
        }

        if(g[node.x+1][node.y]>0&&(!check[node.x+1][node.y]))///下移
        {
            graph w;
            w.x = node.x+1;
            w.y = node.y;
            check[w.x][w.y] = true;
            q.push(w);

        }

        if(g[node.x][node.y-1]>0&&(!check[node.x][node.y-1]))///左移
        {
            graph w;
            w.x = node.x;
            w.y = node.y-1;
            check[w.x][w.y] = true;
            q.push(w);

        }

        if(g[node.x][node.y+1]>0&&(!check[node.x][node.y+1]))///下移
        {
            graph w;
            w.x = node.x;
            w.y = node.y+1;
            check[w.x][w.y] = true;
            q.push(w);

        }

    }

    return false;
}
/*5 5
1 0 0 0 1
1 0 0 1 0
1 1 0 1 1
0 1 1 0 0
0 0 0 1 1
no

4 7
1 1 1 0 1 0 0
1 0 1 1 0 1 0
1 1 0 1 1 1 0
0 0 0 0 0 1 1
yes

*/

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值