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.
n,m represent the maze is a nxm maze.(n rows, m columnsm,0 <n,m <= 21).
Then is the maze.
e.g.
5 5
#####
#S..#
#.!.#
#.#E#
#####
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,用queue来实现:
#include<iostream>
#include<string.h>
#include<queue>
using namespace std;
int bfs();
char maze[22][22];
int visit[22][22];
int s[4][2]= {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int n, m, start1, start2, end1, end2;
struct node{
int x, y, step;
node(int x1, int y1, int step1): x(x1), y(y1), step(step1) {}
};
int main() {
cin>> n>> m;
memset(visit, 0, sizeof(visit));
for (int i= 0; i< n; i++) {
for (int j= 0; j< m; j++) {
cin>> maze[i][j];
if (maze[i][j]== 'S') {
start1= i, start2= j;
}
if (maze[i][j]== 'E') {
end1= i, end2= j;
}
}
}
cout<< bfs();
}
int bfs() {
node f(start1, start2, 0);
queue<node> q;
while (!q.empty()) q.pop();
q.push(f);
while (!q.empty()) {
f= q.front();
q.pop();
if (f.x== end1&&f.y== end2) {
return f.step;
}
visit[f.x][f.y]= 1;
for (int i= 0; i< 4; i++) {
int x= f.x+ s[i][0];
int y= f.y+ s[i][1];
if (x== end1&&y== end2) {
return f.step+ 1;
}
if (x>= 0&&x< n&&y>= 0&&y< m&&maze[x][y]== '.'&&visit[x][y]== 0) {
visit[x][y]= 1;
node next(x, y, f.step+ 1);
q.push(next);
}
}
}
return -1;
}