1.问题简介:
迷宫问题是学习搜索入门很好的一个经典问题,比如给定一个迷宫,给定起点并且给定终点,让你求出起点到终点的最短步数。比如
2.算法分析:
先比较一下dfs和bfs的区别,dfs会比较慢,为什么呢,因为dfs会先从某一行和某一列进行搜索,搜索到底部,而之前也介绍过bfs是一层一层的进行扩散,就是将这个点的能走到的点都访问。
为什么bfs在求最短路的时候快一些呢,因为它是层层扩散,找到的第一条路必然是最短的,如果地图很大,dfs的效率就不如bfs了。
实现:
struct node {
int x, y, d;
node(int xx, int yy, int dd) {
x = xx;
y = yy;
d = dd;
}
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();
}
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]) {
if (maze[tx][ty] == 'T') {
return now.d + 1;
} else {
vis[tx][ty] = true;
q.push(node(tx, ty, now.d + 1));
}
}
retrun -1;
3.源代码:
#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 xx, int yy, int dd) {
x = xx;
y = yy;
d = dd;
}
};
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();
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]) {
if (maze[tx][ty] == 'T') {
return now.d + 1;
} else {
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;
}
欢迎大家关注
ly’s Blog