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.
Input
n,m represent the maze is a nxm maze.
n rows, m columns ,n、m are less than 21.
Then is the maze.
e.g.
Output
You need to give the least steps to walk from start to the end.If it doesn’t exist, then output -1.
e.g.(for the example in input)
4
解题思路:
广度优先搜索BFS。
下面是解决代码:
#include "iostream"
#include "string"
#include "queue"
using namespace std;
struct point {
int x;
int y;
int step;
};
int num, dx[4] = {0, 1, 0, -1}, dy[4] = {-1, 0, 1, 0};
int row, col;
bool is_IN(int x, int y) {
if (x < 0 || y < 0 || x > row || y > col)
return false;
return true;
}
int BFS(char arr[21][21], point start, point end) {
point temp, New;
queue<point> r;
arr[start.x][start.y] = '#';
r.push(start);
while (!r.empty()) {
temp = r.front();
r.pop();
if (temp.x == end.x && temp.y == end.y) {
return temp.step;
} else {
for (int i = 0; i < 4; ++i) {
New.x = temp.x + dx[i];
New.y = temp.y + dy[i];
if (is_IN(New.x, New.y) && (arr[New.x][New.y] == '.' || arr[New.x][New.y] == 'E')) {
arr[New.x][New.y] = '#';
New.step = temp.step + 1;
r.push(New);
}
}
}
}
return -1;
}
int main() {
cin >> row >> col;
char arr[21][21];
for (int i = 0; i < 21; ++i)
for (int j = 0; j < 21; ++j)
arr[i][j] = 0;
for (int i = 0; i < row; ++i)
for (int j = 0; j < col; ++j)
cin >> arr[i][j];
point start, end;
start.step = 0;
for (int i = 0; i < row; ++i)
for (int j = 0; j < col; ++j) {
if (arr[i][j] == 'S') {
start.x = i;
start.y = j;
} else if (arr[i][j] == 'E') {
end.x = i;
end.y = j;
}
}
int min = BFS(arr, start, end);
cout << min << endl;
return 0;
}
值得注意的几点:
1、走过的路要记得做好标记。
2、选用一个struct结构来记录每一步的位置比较清晰,而且在struct里面定义一个step来记录每一步是当前走过的第几步。