题目背景
HI,我是Zac,是一名xxs,有时也是一名平平无奇的程序员。今天我突发奇想,想出一道题,下面是我出的题↓
题目内容
有一天,大名鼎鼎的网络黑客Hecker被网络警察骗入了一个迷宫,结果他一进来就出不去了,可幸运的他捡到了一张地图,他想:“地图……天助我也!”Hecker想用最短的时间逃出去来报复网络警察,所以他请来了你——C++解迷大师。现在,你要帮他写一个程序,来算出他最少要走多少步才能逃出迷宫。
输入格式
第一行一个整数 n,m (4 <= n,m <= 100),表述迷宫的周长。
第二行开始为一个n x m的字符数组,S表示起点,T表示终点,.表示道路,*表示墙壁。
输出格式
输出一行,如果有解,输出网络黑客Hecker最少要走多少步才能逃出迷宫的步数,否则输出-1。
输入样例
5 6
....S*
.**...
.*..*.
*..**.
.T....
输出样例
7
解题思路
好吧,相信各位大神都知道这道题是一道典型的搜索问题。在这里我将为各位提供两种思路的代码。一种是深搜,一种是广搜,上代码!
深搜AC代码
#include <iostream>
#include <cstdio>
using namespace std;
char maze[15][15];
bool vis[15][15];
int n, m, ans;
int dir[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
bool in(int x, int y) {
return x >= 0 && x < n && y >= 0 && y < m;
}
void dfs(int x, int y) {
if (maze[x][y] == 'T') {
ans++;
return ;
}
vis[x][y] = true;
for (int i = 0; i < 4; i++) {
int tx = x + dir[i][0];
int ty = y + dir[i][1];
if (in(tx, ty) && !vis[tx][ty] && maze[tx][ty] != '#') {
dfs(tx, ty);
}
}
vis[x][y] = false;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> maze[i];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (maze[i][j] == 'S') {
dfs(i, j);
}
}
}
cout << ans << endl;
return 0;
}
广搜AC代码
#include <iostream>
#include <string>
#include <queue>
using namespace std;
int n, m;
string maze[110];
bool vis[110][110];
int dir[4][2] = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
bool in(int x, int y) {
return 0 <= x && x < n && 0 <= y && y < m;
}
struct node {
int x, y, d;
node(int _x, int _y, int _d) {
x = _x;
y = _y;
d = _d;
}
};
int bfs(int sx, int sy) {
queue<node> q;
q.push(node(sx, sy, 0));
vis[sx][sy] = true;
while (!q.empty()) {
node now = q.front();
q.pop();
if (maze[now.x][now.y] == 'T') {
return now.d;
}
for (int i = 0; i < 4; i++) {
int tx = now.x + dir[i][0];
int ty = now.y + dir[i][1];
if (in(tx, ty) && maze[tx][ty] != '*' && !vis[tx][ty]) {
vis[tx][ty] = true;
q.push(node(tx, ty, now.d + 1));
}
}
}
return -1;
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
cin >> maze[i];
}
int x, y;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (maze[i][j] == 'S') {
x = i;
y = j;
}
}
}
cout << bfs(x, y) << endl;
return 0;
}
好吧,这就是本题的解题思路,有兴趣的大神可以点赞👍🏼、关注✅、收藏📂一下,拜托了🙏🏼(如果有问题,可以在评论区发表~)。
BYE BYE,我们下期再见!