题目
深搜和广搜模板题
思路
思路一:深度优先搜索
从起点开始,不撞南墙不回头,不走到不能走的位置就不换方向
思路二:广度优先搜索
从起点开始,一步一步地往外探索,一层一层地剥洋葱
代码
// 思路一:深搜
#include <functional>
#include <iostream>
using namespace std;
const char S = 's'; // 起点
const char T = 't'; // 终点
const char X = 'x'; // 障碍物
const int N = 502;
int main(void) {
ios::sync_with_stdio(false);
cin.tie(0);
char maze[N][N];
int t = 0, n = 0, m = 0;
function<bool(int, int)> dfs = [&](int xx, int yy) -> bool {
if (xx < 0 || xx >= n || yy < 0 || yy >= m || maze[xx][yy] == X)
return false;
if (maze[xx][yy] == T) return true;
maze[xx][yy] = X;
return dfs(xx - 1, yy) || dfs(xx, yy - 1) || dfs(xx + 1, yy) ||
dfs(xx, yy + 1);
};
int i = 0, j = 0, x = 0, y = 0;
cin >> t;
while (t--) {
cin >> n >> m;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cin >> maze[i][j];
if (maze[i][j] == S) {
x = i, y = j;
}
}
}
cout << (dfs(x, y) ? "YES" : "NO") << endl;
}
return 0;
}
// 思路二:广搜
#include <iostream>
using namespace std;
const char S = 's'; // 起点
const char T = 't'; // 终点
const char X = 'x'; // 障碍物
const int N = 502;
const int TO[][2]{{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
int main(void) {
// 加上这两句解绑,运行速度会快一倍
ios::sync_with_stdio(false);
cin.tie(0);
int t = 0, n = 0, m = 0;
char maze[N][N];
int q[N * N], h = -1, r = -1; // 数组模拟队列,主要是方便清空
int i = 0, j = 0, x = 0, y = 0, tx = 0, ty = 0;
auto check = [&] {
h = r = -1; // 清空队列
q[++r] = x * 1000 + y;
maze[x][y] = X;
while (h < r) {
x = q[h + 1] / 1000;
y = q[h + 1] % 1000;
h++;
for (i = 0; i < 4; i++) {
tx = x + TO[i][0];
ty = y + TO[i][1];
if (tx < 0 || tx >= n || ty < 0 || ty >= m ||
maze[tx][ty] == X) {
continue;
}
if (maze[tx][ty] == T) return true;
maze[tx][ty] = X;
q[++r] = tx * 1000 + ty;
}
}
return false;
};
cin >> t;
while (t--) {
cin >> n >> m;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
cin >> maze[i][j];
if (maze[i][j] == S) {
x = i, y = j;
}
}
}
cout << (check() ? "YES" : "NO") << endl;
}
return 0;
}