迷宫最短路径问题-BFS
来源:互联网 发布:js 设置css 编辑:程序博客网 时间:2024/05/01 09:47
C++实现:
#include <iostream>#include <string>#include <stdio.h>#include <stdlib.h>#include <queue>using namespace std;const int INF=100;typedef struct node{ int x; int y; int dr; //从上一结点到这个结点的方向 struct node *last;}*NODE;NODE sp=NULL; //开始点NODE gp=NULL; //结束点int N=10,M=10;int sx,sy;int gx,gy;char maze[10][11]={"#.######.#", "......#..#", ".#.##.##.#", ".#........", "##.##.####", "....#....#", ".#######.#", "....#.....", ".####.###.", "....#....#"};int d[10][10];int dx[4]={1,0,-1,0};int dy[4]={0,1,0,-1};int bfs(){ queue<NODE> que; sp = (struct node*)malloc(sizeof(struct node)); for(int i=0;i<N;i++) for(int j=0;j<M;j++) d[i][j]=INF; sp->x=sx;sp->y=sy; sp->dr=0;sp->last=sp; que.push(sp); d[sx][sy]=0; while(!que.empty()){ NODE p1 = que.front();que.pop(); if(p1->x==gx && p1->y==gy){ gp=p1; break; } for(int i=0;i<4;i++){ int nx=p1->x+dx[i],ny=p1->y+dy[i]; if(nx>=0 && nx<N && ny>=0 && ny<M && maze[nx][ny]=='.'&& d[nx][ny]==INF){ NODE p2 = (struct node*)malloc(sizeof(struct node)); p2->x=nx;p2->y=ny; p2->last = p1;p2->dr=i; que.push(p2); d[nx][ny] = d[p1->x][p1->y]+1; } } } return d[gx][gy];}void fuc1(int i,int j){ if( i==0 && j==0 ){ for(int t=0;t<=N+1;t++){ cout<<"■"; } cout<<endl; } if(j==0) cout<<"■";}void fuc2(int i,int j){ if(j==M-1) cout<<"■"; if( i==N-1 && j==M-1 ){ cout<<endl; for(int t=0;t<=N+1;t++){ cout<<"■"; } }}int main(){ for(int i=0;i<N;i++) { for(int j=0;j<M;j++) cout<<maze[i][j]<<" "; cout<<endl; } sx=0;sy=1; gx=N-1;gy=M-2; int res = bfs(); string str[5] = {"↓","→","↑","←","■"}; char s[4] = {'0','1','2','3'}; if(res!=INF) cout<<"最少需要"<<res<<"步到达终点"<<endl; int t = gp->dr; while(gp!=sp){ gp=gp->last; maze[gp->x][gp->y]=s[t]; t=gp->dr; } for(int i=0;i<N;i++) { for(int j=0;j<M;j++){ fuc1(i,j); //加墙壁 if(i==sx && j==sy) cout<<"☆"; else if(i==gx && j==gy) cout<<"★"; else if(maze[i][j]=='#') cout<<str[4]; else if(maze[i][j]=='.') cout<<" "; else{ switch(maze[i][j]) { case '0':cout<<str[0];break; case '1':cout<<str[1];break; case '2':cout<<str[2];break; case '3':cout<<str[3];break; default:cout<<maze[i][j]; } } fuc2(i,j); } cout<<endl; } return 0;}
输出样例:
0 0
- BFS 迷宫的最短路径问题
- 迷宫问题之最短路径bfs
- 迷宫最短路径问题-BFS
- 迷宫最短路径问题(BFS)
- POJ 3984 迷宫问题【迷宫最短路径 bfs】
- 迷宫最短路径(bfs)
- BFS 迷宫最短路径
- BFS解迷宫问题,并打印最短路径
- 回溯法-bfs--迷宫问题的最短路径
- BFS:迷宫的最短路径
- BFS求迷宫的最短路径
- 小白书之迷宫最短路径bfs
- BFS求解迷宫最短路径
- BFS 模板 【迷宫的最短路径】
- 迷宫的最短路径 -- BFS
- BFS 迷宫的最短路径
- 迷宫最短路径长度bfs
- 迷宫的最短路径 (BFS)
- 筛法,欧拉函数,递推(帮帮Tomisu,uva 11440)
- javascript 过几秒自动跳转
- dubbo的详解
- jquery笔记
- 程序员进阶之路,转自知乎(作者:鼬自来晓)
- 迷宫最短路径问题-BFS
- AOP原理
- VNC实现的控制原理
- scala xml操作
- 手机号检测
- Android的按钮监听事件&自定义回调函数
- A trap about .net asynchronous programming
- String.format()用法
- Mysql 死锁发生时的详细分析方法