机器猫被困在一个矩形迷宫里。
迷宫可以视为一个 矩阵,每个位置要么是空地,要么是墙。机器猫只能从一个空地走到其上、下、左、右的空地。
机器猫初始时位于 的位置,问能否走到 位置。
第一行,两个正整数 。
接下来 行,输入这个迷宫。每行输入一个长为 的字符串,#
表示墙,.
表示空地。
仅一行,一个字符串。如果机器猫能走到 ,则输出 Yes
;否则输出 No
。
3 5 .##.# .#... ...#.
Yes
路线如下:
对于 的数据,保证 ,且 和 均为空地。
直接用bfd搜就好
cpp#include <iostream>
#include <queue>
using namespace std;
int n, m;
char maze[105][105];
bool visited[105][105];
// 方向数组,用于BFS遍历
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
bool isValid(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m && maze[x][y] == '.' && !visited[x][y];
}
bool bfs() {
queue<pair<int, int>> q;
q.push({0, 0}); // 从 (1, 1) 开始,但在数组中是 (0, 0)
visited[0][0] = true;
while (!q.empty()) {
auto [x, y] = q.front();
q.pop();
// 如果到达终点 (n, m),返回 true
if (x == n - 1 && y == m - 1) {
return true;
}
// 遍历四个方向
for (int i = 0; i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if (isValid(nx, ny)) {
q.push({nx, ny});
visited[nx][ny] = true;
}
}
}
// 如果遍历完所有可能的路径都没有找到终点,返回 false
return false;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> maze[i][j];
}
}
if (bfs()) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
这种模板题目多练就好了
这题还能用dfs
cpp#include <iostream>
using namespace std;
int n, m;
char maze[105][105];
bool visited[105][105];
// 方向数组,用于DFS遍历
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
bool isValid(int x, int y) {
return x >= 1 && x <= n && y >= 1 && y <= m && maze[x][y] == '.' && !visited[x][y];
}
bool dfs(int x, int y) {
// 如果到达终点 (n, m),返回 true
if (x == n && y == m) {
return true;
}
visited[x][y] = true;
// 遍历四个方向
for (int i = 0; i < 4; ++i) {
int nx = x + dx[i];
int ny = y + dy[i];
if (isValid(nx, ny)) {
if (dfs(nx, ny)) {
return true;
}
}
}
// 如果遍历完所有可能的路径都没有找到终点,返回 false
return false;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
cin >> maze[i][j];
}
}
if (dfs(1, 1)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!