问题描述:
①迷宫由n行m列的单元格组成(n,m都小于等于50)
②每个单元格要么是空地,要么是障碍物
现请你找到一条从起点到终点的最短路径,输出最短路径及其长度,若不存在,则输出“No Answer.”。
输入迷宫大小(n行m列):
5 4
1 1 0 1
1 1 1 1
1 1 0 1
1 0 1 1
1 1 1 0
输入起点的坐标:
0 0
输入终点的坐标:
3 2
输出:
最短路径长度为7
最短路径:
(0,0)
(1,0)
(2,0)
(3,0)
(4,0)
(4,1)
(4,2)
(3,2)
思路:使用BFS算法,首先创建一个空的队列,起点先入列,从起点开始访问,然后访问起点周围的点,判断这些点的状态,如果是未访问的且可通行的点,则该点入列。不断重复上述过程,直到访问到终点返回最短路径,或者直到队列为空,输出“No Answer.”。
代码如下:
#include <iostream>
#include<vector>
#include<queue>
using namespace std;
class Point {
public:
int x;
int y;//坐标
int step;//步数
Point* parent;//父节点
Point() {}
Point(int xx, int yy, int s=0,Point* p=NULL) :x(xx), y(yy), step(s),parent(p) {}
};//构成路径的每个点
vector<vector<int>> maze(int n,int m) {//初始化迷宫
vector<vector<int>> maze(n, vector<int>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j <m; j++) {
maze[i][j] = 1;//初始化可以通过
}
}
maze[0][2] = 0;
maze[2][2] = 0;
maze[3][1] = 0;
maze[4][3] = 0;//设置障碍,这些位置无法通过
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << maze[i][j] << ' ';
}
cout << endl;
}//打印迷宫
return maze;
}
Point* bfs(vector < vector<int>> maze, int n,int m) {
int startx , starty, endx, endy;
cout << "输入起点的坐标:" << endl;
cin >> startx >> starty;
cout << "输入终点的坐标:" << endl;
cin >> endx >> endy;
maze[endx][endy] = 2;//终点坐标
Point* start=new Point(startx,starty, 0,NULL);//起点
vector<vector<int>> visited(n, vector<int>(m, 0));//已访问的点集
queue<Point*> Q;//未访问的点集
Q.push(start);//起点入列
while (!Q.empty()) {//队列变空前
Point* point = Q.front();//取出队首元素
Point* pnew;
visited[point->x][point->y]=1;//标记已访问
if (maze[point->x][point->y]==2) {
return point;
}//到达终点,返回终点指针
//试探所有方向能不能走
if (point->x - 1 == -1||!maze[point->x-1][point->y]);//如果越界或遇到障碍物,跳过
else if(!visited[point->x - 1][point->y]) Q.push(pnew = new Point(point->x - 1, point->y, point->step + 1, point));//否则向上走并入列
if (point->x + 1 == n || !maze[point->x+1][point->y]);//如果越界或遇到障碍物,跳过
else if (!visited[point->x + 1][point->y]) Q.push(pnew = new Point(point->x + 1, point->y, point->step + 1,point));//否则向下走并入列
if (point->y - 1 == -1 || !maze[point->x][point->y-1]);//如果越界或遇到障碍物,跳过
else if (!visited[point->x][point->y - 1]) Q.push(pnew= new Point(point->x, point->y - 1, point->step + 1,point));//否则向左走并入列
if (point->y + 1 == m || !maze[point->x][point->y+1]);//如果越界或遇到障碍物,跳过
else if (!visited[point->x][point->y + 1]) Q.push(pnew = new Point(point->x, point->y + 1, point->step + 1,point));//否则向右走并入列
Q.pop();//访问完毕,出列
}
return NULL;//没有路径,返回空指针
}
void way(Point* tail){
if (!tail) return;//起点的父节点为空,返回
way(tail->parent);//递归访问父节点
cout << "(" << tail->x << "," << tail->y << ")" << endl;//从起点开始输出
}
int main()
{
int n, m;
cout << "输入迷宫大小(n行m列):" << endl;
cin >> n >> m;//输入迷宫大小:n行m列
Point* node = bfs(maze(n,m), n,m);//接受最终的点指针
if (!node) cout << "No Answer."<<endl;//接收空指针,没有路径
else {//否则接收终点指针
cout <<"最短路径长度为"<< node->step << endl;//输出最短路径距离
cout << "最短路径:" << endl;
way(node);//输出最短路径
}
return 0;
}
运行结果: