迷宫(BFS)
标签: 算法
题目描述
You are provided a maze(迷宫), and you need to program to find the least steps to walk from the start to the end.And you can only walk in four directions:up, down,left, right.
There will only be 5 kinds of characters in the maze.The meaning of each is as followed.
“#” is for rock, which you can not walk through.
“S” is for start.
“E” is for end.
“.” is for road.
“!” is for magma(岩浆),which you can not walk through.
e.g.
#####
#S..#
#.!.#
#.#E#
#####
算法实现
首先将出发点压入队列,从此节点开始探索,由它产生的可能四个方向,如果走得通,就将其压入队列。每次从队列拿出一个节点,循环上次步骤直至队列为空或者到达终点。
代码实现
#include <iostream>
#include <queue>
using namespace std;
char maze[100][100];
int dir[4][2] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; //用数组来代替位移w, s, a, d
struct Node {
int x, y;
int step; //步数记录
Node(int x_, int y_, int step_): x(x_), y(y_), step(step_) {}
};
int SearchTheWay(int s_x, int s_y,
int e_x, int e_y,
int m_m, int m_n) {
Node node(s_x, s_y, 0);
queue<Node> q;
q.push(node);
while (!q.empty()) {
node = q.front();
q.pop();
if (node.x == e_x && node.y == e_y) //如果该点为终点
return node.step;
maze[node.y][node.x] = '#';
for (int i = 0; i < 4; i++) {
int x = node.x + dir[i][0]; //通过循环来遍历wsad四个方向
int y = node.y + dir[i][1];
if (x >= 0 && y >= 0 && x <= m_m && y <= m_n &&
(maze[y][x] == '.' || maze[y][x] == 'E')) {
maze[y][x] = '#'; //将走过的路换成墙,防止回溯
Node temp(x, y, node.step + 1); //注意step+1这一细节
q.push(temp);
}
}
}
return -1; //如果无路,则返回-1
}
int main() {
int m, n;
int start_x, start_y;
int end_x, end_y;
cin >> m >> n;
for (int i = 0; i < m; i++)
cin >> maze[i];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (maze[i][j] == 'S') {
start_x = j;
start_y = i;
}
if (maze[i][j] == 'E') {
end_x = j;
end_y = i;
}
}
}
int result = SearchTheWay(start_x, start_y, end_x, end_y, n, m);
cout << result << endl;
return 0;
}