AcWing 844. 走迷宫
原题链接
简单
作者:
一抹斜阳
,
2019-12-12 08:17:33
,
所有人可见
,
阅读 924
#include<iostream>
using namespace std;
#include<queue>
int m, n;
struct point
{
int x, y;
int d;
point(int a, int b, int c) :x(a), y(b), d(c)
{
}
};
const int MAX = 101;
int maze[MAX][MAX];
int used[MAX][MAX];
int bfs();
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> maze[i][j];
cout << bfs() << endl;
return 0;
}
int bfs()
{
queue<point>q;
q.push(point(1, 1, 0));
while (!q.empty())
{
point p = q.front();
if (p.x == n && p.y == m)
{
return p.d;
}
else
{
if (p.x - 1 >= 1 && maze[p.x - 1][p.y] == 0 && used[p.x - 1][p.y] == 0) //上
{
q.push(point(p.x - 1, p.y, p.d + 1));
used[p.x - 1][p.y] = 1;
}
if (p.x + 1 <= n && maze[p.x + 1][p.y] == 0 && used[p.x + 1][p.y] == 0) //下
{
q.push(point(p.x + 1, p.y, p.d + 1));
used[p.x + 1][p.y] = 1;
}
if (p.y - 1 >= 1 && maze[p.x][p.y - 1] == 0 && used[p.x][p.y - 1] == 0) //左
{
q.push(point(p.x, p.y - 1, p.d + 1));
used[p.x][p.y - 1] = 1;
}
if (p.y + 1 <= m && maze[p.x][p.y + 1] == 0 && used[p.x][p.y + 1] == 0) //右
{
q.push(point(p.x, p.y + 1, p.d + 1));
used[p.x][p.y + 1] = 1;
}
}
q.pop();
}
}