迷宫最短路径的C++实现(队列:广度优先)
2012-04-24 22:46
781 查看
#include<iostream> #include<queue> #include<string> using namespace std; struct point{ int x; int y; point *last;//上一步的坐标 }; int main(){ while(1){ int row, col, i, j; cout<<"请输入迷宫图的行数和列数:"; cin>>row>>col; int **a = new int* [row+2]; for(i = 0; i < row+2; ++i){ a[i] = new int[col+2]; } cout<<"请输入迷宫图(1代表墙壁,0代表通路):"<<endl; for(i = 1; i < row+1; ++i){ for(j = 1; j < col+1; ++j){ cin>>a[i][j]; } } for(i = 0; i < col+2; ++i){//加墙 a[0][i] = 1; a[row+1][i] = 1; } for(i = 1; i < row+1; ++i){//加墙 a[i][0] = 1; a[i][col+1] = 1; } queue<point*> q; point *start = (point*)malloc(sizeof(point));//起点 cout<<"请输入起点坐标(范围1,1到"<<row<<","<<col<<"):"; cin>>start->x>>start->y; start->last = start; q.push(start); a[start->x][start->y] = 2; point end;//终点 cout<<"请输入终点坐标(范围1,1到"<<row<<","<<col<<"):"; cin>>end.x>>end.y; int aspect[4][2] = {{0, -1},{0, 1},{-1, 0},{1, 0}};//转向:上下左右 int flag = 0;//是否有路可走的标志 while(!q.empty()){ point *front = q.front(); q.pop();//弹出队头 if(front->x == end.x && front->y == end.y){ flag = 1; cout<<"成功找到出路."<<"最少需要"<<a[front->x][front->y]-2<<"步。如下所示:"<<endl; a[front->x][front->y] = -6; //cout<<"倒退回去:"<<(front)->x<<","<<(front)->y; point *lastPoint = front; front = front->last; while((front->x != start->x) || (front->y != start->y)){ //cout<<"->"<<front->x<<","<<front->y; if(lastPoint->x - front->x == 1){ a[front->x][front->y] = -1; }else if(lastPoint->x - front->x == -1){ a[front->x][front->y] = -2; }else if(lastPoint->y - front->y == 1){ a[front->x][front->y] = -3; }else{ a[front->x][front->y] = -4; } lastPoint = front; front = front->last; } //cout<<"->"<<start->x<<","<<start->y<<endl; a[start->x][start->y] = -5; break; }else{ for(int i = 0; i < 4 ; ++i){ point *temp = new point; temp->x = front->x + aspect[i][0]; temp->y = front->y + aspect[i][1]; if(a[temp->x][temp->y] == 0){ temp->last = front; q.push(temp); a[temp->x][temp->y] = a[front->x ][front->y] + 1; } } } } if(!flag) cout<<"无路可走!"<<endl; else{ string s[6] = {"★", "☆", "←","→","↑","↓" }; for(int i = 0; i < 11; ++i){ for(int j = 0; j < 10; ++j){ if(a[i][j]==1){ cout<<"■"; }else if(a[i][j]<0){ int temp = a[i][j]+6; cout<<s[temp]; }else{ cout<<" "; } } cout<<endl; } } system("pause"); } }
测试数据
9 8 0 0 1 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 1 0 1 1 1 1 0 0 1 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0运行结果:
相关文章推荐
- 迷宫最短路径的C++实现(队列:广度优先)
- 广度优先搜索--迷宫最短路径--队列
- 算法基础(六):广度优先探索迷宫路径(队列实现!)—超详细版!
- 迷宫问题(广度优先搜索,输出最短路径)
- C++利用队列(Queue)求解迷宫(Maze)中指定起点和终点间是否有最短路径,如果有的话输出所需步数,如果没有输出
- 迷宫:广度优先搜索求最短路径
- Java实现利用广度优先遍历(BFS)计算最短路径的方法
- 利用广度优先遍历(BFS)计算最短路径 - Java实现
- c++ 使用广度优先算法走迷宫并标记路径
- 用邻接表实现图的深度优先遍历、广度优先遍历、最短路径(无权图)
- 广度优先搜索迷宫的最短路径走法!
- zoj1649-Rescue (迷宫最短路径)【bfs 优先队列】
- 广度优先搜索迷宫路径算法的实现
- 广度优先搜索 最短路径 队列
- 队列实现求迷宫最短路径(包含每一步的尝试状态,迷宫随机生成)
- C++非递归队列实现二叉树的广度优先遍历
- (广度优先搜索第一课)迷宫的最短路径 - BFS
- C++实现图的邻接矩阵的创建以及其深度优先遍历和广度优先遍历
- 算法导论 第六章优先队列C++实现
- 求图中最短路径算法之Floyd-Warshall算法——C++实现