迷宫寻宝
题目
一个叫ACM的寻宝者找到了一个藏宝图,它根据藏宝图找到了一个迷宫,不限时间和步数,当然也没有陷阱,请你判断他能不能顺利的得到宝藏。
输入
多组输入
每组测试数据的第一行包含了两个整数M,N(1<N,M<20)(n=0&&m=0表示输入结束),分别代表了迷宫的行和列。接下来的M每行有N个字符,描述了迷宫的布局。其中每个字符的含义如下:
.表示可以走的路
S:表示ACM的出发点
G表示宝藏的位置
#表示这里有墙,ACM无法进入或者穿过。
输出
每行输出一个YES表示ACM能找到宝藏,输出NO表示ACM找不到宝藏。
样例输入
4 4
S.#.
..#.
..#G
..#.
3 4
S.#.
..#.
...G
0 0
样例输出
NO
YES
代码流程
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
#define endl '\n'
using ll=long long;
const size_t maxn = 101;
char a[maxn][maxn];
bool book[maxn][maxn];
int m, n;
int fx[4][2] = {{0, 1},
{0, -1},
{1, 0},
{-1, 0}};//定义方向数组,宽度搜索向领域拓展
struct Node {
int x, y, z;
};//构造结构体包含横纵坐标及路径
void bfs(int sx, int sy, int ex, int ey) {
queue<Node> Q;
Q.push({sx, sy, 0});//进队列
book[sx][sy] = true;//标记数组
while (Q.size()) {
auto &pt = Q.front();//定义队头位置
int x = pt.x;
int y = pt.y;
int z = pt.z;
if (x == ex && y == ey) {
cout << "YES" << endl;
return;
}
Q.pop();//移出队列
for (int i = 0; i < 4; i++) {
int nx = x + fx[i][0];
int ny = y + fx[i][1];
if (nx < 1 || nx > m || ny < 1 || ny > n || book[nx][ny] || a[nx][ny] == '#')continue;
book[nx][ny] = true;
Q.push({nx, ny, z + 1});
book[nx][ny] = true;
}
}
cout << "NO" << endl;
return;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
//freopen("1.txt", "r", stdin);
while (cin >> m >> n) {
if (m == 0 && n == 0)break;
int sx, sy, ex, ey;
memset(book, 0, sizeof(book));//对标记数组进行初始化
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++) {
cin >> a[i][j];
if (a[i][j] == 'S') {
sx = i, sy = j;
}
if (a[i][j] == 'G') {
ex = i, ey = j;
}//标记好起始位置的横纵坐标
}
bfs(sx, sy, ex, ey);//调用宽搜输出
}
return 0;
}