广搜bfs,原理是将周围的可行路径放入队列中,同时判断
用到了上一篇中的myqueue
打印路径的版本
#include <iostream>
#include <ctime>
#include <cstring>
#include "myqueue"
#include "mystack"
#define MAXROW 10
#define MAXLINE 10
using namespace std;
typedef struct _Point
{
int _x;
int _y;
}Point;
int maze[MAXROW][MAXLINE] = {
1,1,1,1,1,1,1,1,1,1,
0,0,0,1,1,1,1,1,1,1,
1,1,0,1,1,1,1,1,1,1,
1,1,0,0,0,0,1,1,1,1,
1,1,0,1,1,0,1,1,1,1,
1,1,0,1,1,0,1,1,1,1,
1,1,0,1,1,0,1,1,1,1,
1,1,0,1,1,0,0,0,1,1,
1,1,0,0,0,1,1,0,0,0,
1,1,1,1,1,1,1,1,1,1,
};
Point sp = {1, 0}, ep = {8, 9};
Point prePts[MAXROW][MAXLINE];
Queue s; // 创建队列
// 绘制函数
void displyMaze(){
for(int i=0; i< MAXROW; i++){
for(int j=0; j<MAXLINE; j++) {
if(maze[i][j] == 1) printf("%2s"," *");
else if(maze[i][j] == 2) printf("%2s"," #");
else printf("%2s"," ");
}
putchar(10);
}
printf(" ====================\n");
}
// 延时函数
void delay(int sec){
time_t start_time, cur_time;
time(&start_time);
do{
time(&cur_time);
}while((cur_time-start_time) < sec);
}
// 在结束的时候打印路径 - 用到了栈
void displyPath(){
Stack s1;
initStack(&s1);
Point t = ep;
do{
push(&s1, t);
t = prePts[t._x][t._y];
}while(t._x!=sp._x || t._y!=sp._y); // t._y!=-1
while(!isStackEmpty(&s1)){
t = pop(&s1);
cout << "(" << t._x << ", " << t._y << ") ";
}
cout << endl;
}
void visit(int x, int y, Point pre){
Point p = {x, y};
enQueue(&s, p);
prePts[x][y] = pre;
}
int main(int argc, char const *argv[])
{
initQueue(&s);
enQueue(&s, sp);
int flag = 0;
Point t;
while(!isQueueEmpty(&s)){
t = deQueue(&s); // 如果栈非空,就弹出栈中的元素作为方向
maze[t._x][t._y] = 2; // 表示走过的路
// 绘制实时路径
system("clear");
displyMaze();
delay(1);
if (t._y-1 >= 0 && maze[t._x][t._y-1]==0) // 左
{
visit(t._x, t._y-1, t);
}
if (t._y+1 <= 9 && maze[t._x][t._y+1]==0) // 右
{
visit(t._x, t._y+1, t);
}
if (t._x-1 >= 0 && maze[t._x-1][t._y]==0) // 上
{
visit(t._x-1, t._y, t);
}
if (t._x+1 <= 9 && maze[t._x+1][t._y]==0) // 下
{
visit(t._x+1, t._y, t);
}
if (t._x == ep._x && t._y == ep._y)
{
flag = 1;
clearQueue(&s);
break;
}
}
if (flag==1)
{
cout << "find path" << endl;
}else{
cout << "NOT find" << endl;
}
displyPath();
return 0;
}