AcWing 844. 走迷宫(入门)

题目链接:点击这里
在这里插入图片描述
在这里插入图片描述

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>

#define x first
#define y second

using namespace std;
typedef pair<int,int> PII;
const int N = 110, M = N * N;

int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};

int n, m;
int g[N][N];
int d[N][N];
PII q[M];

int bfs()
{
    int hh = 0, tt = -1;
    memset(d, -1, sizeof d);
    
    q[++tt] = {0, 0};
    d[0][0] = 0;
    
    while(hh <= tt)
    {
        PII t = q[hh++];
        
        for(int i = 0; i < 4; ++i)
        {
            int nx = t.x + dx[i], ny = t.y + dy[i];
            
            if(nx < 0 || nx >= n || ny < 0 || ny >= m)  continue;
            if(g[nx][ny] == 1)  continue;
            if(d[nx][ny] != -1) continue;
            
            q[++tt] = {nx, ny};
            d[nx][ny] = d[t.x][t.y] + 1;
        }
    }
    
    return d[n-1][m-1];
}


int main()
{
    scanf("%d%d", &n, &m);
    
    for(int i = 0; i < n; ++i)
        for(int j = 0; j < m; ++j)
            scanf("%d", &g[i][j]);
    
    printf("%d\n", bfs());
    
    return 0;
}
发布了844 篇原创文章 · 获赞 135 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/105059731