BFS迷宫搜索路径

 #include<graphics.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
#include<vector>
#include<queue>
#include<stack>
#include<iostream>
#include <algorithm> using namespace std; struct point{
//横坐标纵坐标
int x;
int y;
};
int **Maze; //初始化迷宫
point **Pre; //保存任意点在路径中的前一步
point move[]={{-,-},{-,},{-,},{,-},{,},{,-},{,},{,}}; //移动方向,横竖斜都可以,八个方向
char s1[]="YES";
char s2[]="NO"; void create_line(int row ,int column)//划线
{
int x, y; // 画格子
for (x=; x<=*(row+); x+=)
for (y=; y<=*(column+); y+=)
{
line(x, , x, *(column+));
line(, y,*(row+), y);
}
} void CreateTable(int row,int column)//初始化创建迷宫障碍区
{
int i,j;
srand((unsigned int)time(NULL));
for(i=; i<row+; i++)//创建迷宫,注意到用0表示可走,1表示墙,将整个输入的迷宫再用墙围着,处理的时候就不用特别注意边界问题
{
Maze[i][] = Maze[i][column+] = ;
}
for(j=; j<column+; j++)
{
Maze[][j] = Maze[row+][j] = ;
} for(i=;i<=row;i++)
for(j=;j<=column;j++)
{
Maze[i][j]=rand()%;
} for(i=;i<=row;i++)
for(j=;j<=column;j++)
{
if(Maze[i][j]==)
Maze[i][j]=rand()%;
} for(i=;i<=row+;i++)
for(j=;j<=column+;j++)
{
if(Maze[i][j]==)
{
setfillcolor(WHITE);
fillrectangle(*j,(+*i),(+*j),*i);
}
}
} bool MazePath(int row,int column,int x,int y){
//判断是否有路径从入口到出口,保存该路径(队列)
if(x == row && y == column)return true;
queue<point> q; //用于广度优先搜索
point now; //当前位置
now.x = x;
now.y = y;
q.push(now);
Maze[now.x][now.y] = -;
while(!q.empty()){
now = q.front();
q.pop();
for(int i=; i<; i++){
if(now.x + move[i].x == row && now.y + move[i].y == column){
Maze[now.x + move[i].x][now.y + move[i].y] = -;
Pre[row][column] = now;
return true;
}
if(Maze[now.x + move[i].x][now.y + move[i].y] == ){
point temp; //下个位置
temp.x = now.x + move[i].x;
temp.y = now.y + move[i].y;
q.push(temp);
Maze[temp.x][temp.y] = -;
Pre[temp.x][temp.y] = now; }
}
}
return false;
} void PrintPath(int row,int column){
//输出最短路径
point temp; //保存位置
stack<point> s; //保存路径序列
temp.x = row;
temp.y = column;
while(temp.x != || temp.y != ){
s.push(temp);
temp = Pre[temp.x][temp.y];
}
setfillcolor(YELLOW);
fillrectangle(*,(+*),(+*),*);
while(!s.empty()){
temp = s.top();
setfillcolor(YELLOW);
fillrectangle(*temp.y,(+*temp.x),(+*temp.y),*temp.x);
s.pop();
}
cout<<endl;
} void result(int row,int column)
{
if(MazePath(row,column,,))
{
//outtextxy(320,320,s1);
PrintPath(row,column);
}
else outtextxy(,,s2);
} void Init(int row,int column)
{
Maze = new int*[row + ];
Pre = new point*[row + ];
for(int i=; i<row+; i++)
{
Maze[i] = new int[column + ];
Pre[i] = new point[column + ];
}
} void main()
{
int row,column;
cin>>row>>column;
Init(row,column);
initgraph(,);
BeginBatchDraw();
setlinecolor(GREEN);//设置字体颜色
create_line(column,row);
CreateTable(row,column);
result(row,column);
FlushBatchDraw();
EndBatchDraw();
getch();
closegraph();
}

BFS迷宫搜索路径

上一篇:easyui 后台页面,在Tab中的链接点击后添加一个新TAB的解决方法


下一篇:Linux磁盘操作命令