宽度优先搜索 最短路径
2017-11-20 21:17
281 查看
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<vector> #include<map> #include<queue> #include<set> #define maxn 105 #define LL long long #define lson step<<1 #define rson step<<1|1 #define INF 4294967295 using namespace std; int n,m; int sx,sy,gx,gy; struct node { int x,y,s;//s为路径长度 }; char mapp[maxn][maxn]; bool book[maxn][maxn]; void input() { for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin>>mapp[i][j]; } } } void bfs(int sx,int sy,int gx,int gy) { int next[4][2]={{0,1},{1,0},{-1,0},{0,-1}}; int tx,ty; node h,fw; h.x=sx;h.y=sy;h.s=0; queue<node>q; q.push(h); int flag=0; while(!q.empty()) { h=q.front(); q.pop(); for(int k=0;k<4;k++) { tx=h.x+next[k][0]; ty=h.y+next[k][1]; if(tx<0||tx>=n||ty<0||ty>=m) continue; if(mapp[tx][ty]=='.'&&book[tx][ty]==false) { fw.x=tx; fw.y=ty; fw.s=h.s+1; book[tx][ty]=true; q.push(fw); } if(tx==gx&&ty==gy) { flag=1; break; } } if(flag) break; } cout << fw.s << endl; } int main() { ios_base::sync_with_stdio(false); cin>>n>>m; input(); memset(book,false,sizeof(book)); cin>>sx>>sy>>gx>>gy; sx--;sy--;gx--;gy--; bfs(sx,sy,gx,gy); return 0; }
相关文章推荐
- 宽度优先搜索——迷宫的最短路径
- 白书2.1.5宽度优先搜索(迷宫的最短路径)
- 迷宫最短路径(宽度搜索妙解)
- 算法之------深度优先搜索DFS和广度优先搜索BFS(最短路径)
- 图论(三)------广度优先搜索与单源无权最短路径
- python宽度优先搜索算法并输出路径
- (原创)广度优先搜索解决最短路径问题
- BFS-迷宫问题-用宽度(广度)优先搜索解决最优路径问题
- 迷宫最短路径 深度优先搜索—C—python
- 宽度搜索(BFS)中求最短路径问题理解记录
- 从拓扑排序到广度优先搜索到单源最短路径
- (广度优先搜索第一课)迷宫的最短路径 - BFS
- 宽度搜索优先算法搜索迷宫最短距离
- c语言描述之广度优先搜索——无权最短路径
- 迷宫问题(广度优先搜索,输出最短路径)
- 宽度优先搜索(记录路径)
- 图论(三)------广度优先搜索与单源无权最短路径
- 广度优先搜索之最短路径
- 广度优先搜索--迷宫最短路径--队列
- BFS-迷宫问题-用宽度(广度)优先搜索解决最优路径问题