题意:分别找出从S到E的左路优先、右路优先、最短路的step。
思路:dfs+bfs.
#include<iostream> #include<cstdio> #include<string> #include<queue> using namespace std; #define N 45 char maze[N][N]; bool vis[N][N],flag; int n,m,leftstep,rightstep; int leftdir[][2]={{0,-1},{-1,0},{0,1},{1,0}}; int rightdir[][2]={{0,1},{-1,0},{0,-1},{1,0}}; class point { public: int x,y; int step; }; bool boundary(point a) { if(a.x >=0&&a.x<n&&a.y >=0&&a.y <m) return true; return false; } int shortest(point st,point ed) { int i,j,k; int dir[][2]={{0,-1},{0,1},{-1,0},{1,0}}; queue<point >q; memset(vis,true,sizeof(vis)); point node,p; node=st;node.step =1; vis[node.x ][node.y ]=false; q.push (node); while(!q.empty()) { node=q.front ();q.pop (); for(i=0;i<4;i++) { p.x =node.x +dir[i][0]; p.y =node.y +dir[i][1]; if(boundary(p)&&vis[p.x ][p.y ]&&maze[p.x ][p.y ]!='#') { vis[p.x ][p.y ]=false; p.step =node.step +1; if(p.x ==ed.x &&p.y ==ed.y ) return p.step ; q.push (p); } } } } void leftdfs(point st,point ed,int di,int step) { point node,p; int i; if(flag) return ; if(st.x ==ed.x &&st.y==ed.y ) { flag=true; leftstep=step; return ; } node=st; for(i=0;i<4;i++) { p.x =node.x +leftdir[(di+3+i)%4][0]; p.y =node.y +leftdir[(di+3+i)%4][1]; if(flag ) return ; if(boundary(p)&&maze[p.x ][p.y ]!='#') leftdfs(p,ed,(di+3+i)%4,step+1); } } void rightdfs(point st,point ed,int di,int step) { point node,p; int i; if(flag) return ; if(st.x==ed.x&&st.y ==ed.y ) { flag=true; rightstep=step; return ; } node=st; for(i=0;i<4;i++) { p.x =node.x+rightdir[(di+3+i)%4][0]; p.y =node.y+rightdir[(di+3+i)%4][1]; if(flag) return; if(boundary(p)&&maze[p.x ][p.y ]!='#') rightdfs(p,ed,(di+3+i)%4,step+1); } } int main() { int t,i,j; point st,ed; cin>>t; while(t--) { cin>>m>>n; for(i=0;i<n;i++) scanf("%s",&maze[i]); for(i=0;i<n;i++) for(j=0;j<m;j++) { if(maze[i][j]=='S') { st.x =i;st.y =j; } else if(maze[i][j]=='E') { ed.x =i;ed.y =j; } } point node=st,p; leftstep=0;rightstep=0; for(i=0;i<4;i++) { p.x=node.x +leftdir[i][0]; p.y=node.y +leftdir[i][1]; if(boundary(p)&&maze[p.x ][p.y ]!='#') { flag=false; leftdfs(st,ed,i,1); break; } } for(i=0;i<4;i++) { p.x =node.x +rightdir[i][0]; p.y =node.y +rightdir[i][1]; if(boundary(p)&&maze[p.x ][p.y ]!='#') { flag=false; rightdfs(st,ed,i,1); break; } } cout<<leftstep<<" "<<rightstep<<" "; cout<<shortest(st,ed)<<endl; } return 0; }
迷宫路径算法
本文介绍了一种使用深度优先搜索(DFS)和广度优先搜索(BFS)解决迷宫问题的方法,旨在寻找从起点到终点的左路优先、右路优先及最短路径。通过定义方向数组来控制搜索方向,实现对不同路径的探索。
134

被折叠的 条评论
为什么被折叠?



