AcWing 844. 走迷宫
原题链接
简单
作者:
lemoba
,
2024-11-02 22:20:20
,
所有人可见
,
阅读 1
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
typedef pair<int , int> PII;
const int N = 110;
int n, m;
int g[N][N];
int dis[N][N];
PII q[N * N];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int bfs()
{
int hh = 0, tt = 0;
memset(dis , -1 , sizeof dis);
dis[0][0] = 0;
q[0] = { 0 , 0 };
while(hh <= tt)
{
PII tmp = q[hh ++];
for (int k = 0;k < 4;k ++)
{
int x = tmp.first + dx[k],y = tmp.second + dy[k];
if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && dis[x][y] == -1)
{
dis[x][y] = dis[tmp.first][tmp.second] + 1;
q[++ tt] = { x , y };
}
}
}
return dis[n - 1][m - 1];
}
int main()
{
cin >> n >> m;
for(int i = 0;i < n;i ++)
{
for(int j = 0;j < m;j ++)
{
cin >> g[i][j];
}
}
cout << bfs() << endl;
return 0;
}