- 题解
B3625 迷宫寻路 只得40分自己也查不出错
- 2024-3-17 20:34:25 @
题目描述 机器猫被困在一个矩形迷宫里。 迷宫可以视为一个 n×mn\times m n×m 矩阵,每个位置要么是空地,要么是墙。机器猫只能从一个空地走到其上、下、左、右的空地。 机器猫初始时位于 (1,1)(1, 1) (1,1) 的位置,问能否走到 (n,m)(n, m) (n,m) 位置。 输入格式 第一行,两个正整数 n,mn,m n,m。 接下来 nn n 行,输入这个迷宫。每行输入一个长为 mm m 的字符串,# 表示墙,. 表示空地。 输出格式 仅一行,一个字符串。如果机器猫能走到 (n,m)(n, m) (n,m),则输出 Yes;否则输出 No。 输入输出样例 输入 #1 复制 3 5 .##.# .#... ...#. 输出 #1 复制 Yes 说明/提示 样例解释 路线如下: (1,1)→(2,1)→(3,1)→(3,2)→(3,3)→(2,3)→(2,4)→(2,5)→(3,5)(1,1)\to (2,1) \to (3,1) \to (3,2)\to (3,3) \to (2, 3) \to (2, 4) \to (2, 5) \to (3, 5) (1,1)→(2,1)→(3,1)→(3,2)→(3,3)→(2,3)→(2,4)→(2,5)→(3,5) 数据规模与约定 对于 100%100% 100% 的数据,保证 1≤n,m≤1001 \leq n, m \leq 100 1≤n,m≤100,且 (1,1)(1,1) (1,1) 和 (n,m)(n, m) (n,m) 均为空地。 ''' /* 3 5 .##.# .#... ...#. */
#include #include
typedef struct { int x, y; } Node;
const int wc = 4; Node w[wc] { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int main() { using namespace std;
int n, m;
cin >> n >> m;
char** a = new char*[n];
for (int i = 0; i < n; i++)
{
a[i] = new char[m];
for (int j = 0; j < m; j++)
{
//cin >> a[i][j];
do { cin >> a[i][j]; }
while (a[i][j] != '.' && a[i][j] != '#');
}
}
queue<Node> q;
q.push({0, 0});
try
{
while (!q.empty())
{
Node f = q.front();
if (a[f.x][f.y] == '#') throw false;
a[f.x][f.y] = '#';
for (int i = 0; i < wc; i++)
{
Node node = f;
node.x += w[i].x;
node.y += w[i].y;
if ((node.x < n && node.x >= 0) && (node.y < m && node.y >= 0)) if (a[node.x][node.y] == '.')
{
q.push(node);
if (node.x == n - 1 && node.y == m - 1) throw true;
}
}
q.pop();
}
throw false;
}
catch (bool& r)
{
if (r) cout << "Yes" << endl;
else cout << "No" << endl;
}
for (int i = 0; i < n; i++) delete [] a[i];
delete [] a;
return 0;
} '''