#include<iostream>
#include<queue>
#include<iomanip>
using namespace std;
struct Point
{
int x;
int y;
};//点坐标
const int height = 10;//迷宫的高
const int width = 10;//迷宫的宽
const int maze[height][width] = {
{1,1,0,1,1,1,0,1,0,0},
{0,1,1,1,0,0,0,1,1,1},
{0,0,1,1,0,1,1,1,0,0},
{1,0,1,1,0,1,1,1,1,0},
{1,1,1,1,1,1,0,1,1,0},
{0,0,0,1,0,0,0,1,1,0},
{1,0,1,1,0,1,1,1,1,1},
{1,0,0,1,0,1,0,1,1,0},
{1,0,1,1,1,1,0,0,1,0},
{1,1,1,1,0,1,0,0,1,1}
};//迷宫
enum {UP=1,LEFT,DOWN,RIGHT};//方向
#define WHITE 0
#define GRAY 1
int length[height][width];//记录从起点到各个点的最小长度,初始化为无穷大
int Color[height][width]{WHITE};//记录点是否走过
int Rec[height][width]{0};//记录坐标(x,y)从哪个方向走来
const Point origin = { 0,0 };//起点坐标
const Point destination = { height - 1,width - 1 };//终点坐标
const Point direction[4] = {{0,-1},{-1,0},{0,1},{1,0}};//方向
bool iswall(int x,int y);//检查是否撞墙或者越界
void Solve();
void Road(int x,int y);//路线输出
int main()
{
memset(length, 127, sizeof(length));
Solve();
cout << "最短路径长度: " <<length[destination.y][destination.x] << endl;
Road(width - 1, height - 1);
return 0;
}
void Solve()
{
queue<Point> Queue;
Queue.push(origin);//起点入队
Color[origin.y][origin.x] = GRAY;
length[origin.y][origin.x] = 0;//自己到自己的距离为0
//Rec[origin.y][origin.x] = 0;//没有其它点到起始坐标
while (Queue.size()&&(Queue.front().x!=destination.x)||(Queue.front().y!=destination.y))
//队列不为空,并且队首存储的点坐标不为终点坐标,则循环继续
{
Point target = Queue.front();//取出队首点坐标
for (int i = 1; i <= 4; i++)//四个方向依次搜索
{
int next_x = target.x + direction[i - 1].x;
int next_y = target.y + direction[i - 1].y;
if (!iswall(next_x, next_y) && Color[next_y][next_x] == WHITE)
//保证下一步的点不能撞墙或越界且没有走过
{
Color[next_y][next_x] = GRAY;
if (length[target.y][target.x] + 1 < length[next_y][next_x])
//新的路径比原有路径短(注意不能是等于)
{
length[next_y][next_x] = length[target.y][target.x] + 1;//用新的路径替换原有路径
/*这里不用考虑边的关系,只要这个点被走过了,那么这个点接下来就没有用了。
在这里,边的权值都为1,队列操作,使得先得到的更新的路径一定是最短之一,
等于的情况舍去,可以避免死循环。*/
Rec[next_y][next_x] = i;//记录走来的方向
Queue.push({ next_x,next_y });
}
}
}
Queue.pop();
}
return;
}
bool iswall(int x, int y)
{
if ((x < 0) || (x >= width) || (y < 0) || (y >= height) || (maze[y][x] == 0))
//(x < 0) || (x >= width) || (y < 0) || (y >= height)越界
//maze[y][x] == 0撞墙
return true;
else
return false;
}
void Road(int x, int y)
{
if ((x == origin.x) && (y == origin.y))
return;
if (Rec[y][x] == UP)
{
Road(x, y + 1);
cout << "往上走一步"<<endl;
}
else if (Rec[y][x] == LEFT)
{
Road(x + 1, y);
cout << "往左走一步" << endl;
}
else if (Rec[y][x] == DOWN)
{
Road(x, y - 1);
cout << "往下走一步" << endl;
}
else
{
Road(x - 1, y);
cout << "往右走一步" << endl;
}
return;
}
迷宫BFS
最新推荐文章于 2022-05-31 20:29:08 发布