题意:给一张地图,分别求向左优先、向右优先、最短路三种走法从起点到终点的步数;
思路:向左向右采用dfs,最短路采用bfs;
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; char mm[550][505],flag; int n,m,s1,s2,e1,e2,i,j,k,step1,step2,step3; int vis[550][550]; int shortest[550][550]; int x[4]={1,0,-1,0}; int y[4]={0,1,0,-1}; int xx[4]={1,0,-1,0}; int yy[4]={0,-1,0,1}; struct node { int x,y; node(){}; node(int x,int y){ this->x=x; this->y=y; } }q[100005]; void dfs1(int k1,int k2,int dir,int step) { if(mm[k1][k2]=='E') { printf("%d",step); flag=1;return; } for(i=dir;i<4;i++) { if(flag) break; int x1=k1+xx[i]; int y1=k2+yy[i]; if(mm[x1][y1]!='#'&&x1>0&&x1<=n&&y1>0&&y1<=m) { dir=(i+3)%4; dfs1(x1,y1,dir,step+1); } if(i==3) i-=4; } } void dfs2(int k1,int k2,int dir,int step) { if(mm[k1][k2]=='E') { printf(" %d",step); flag=1;return; } for(i=dir;i<4;i++) { if(flag) break; int x1=k1+x[i]; int y1=k2+y[i]; if(mm[x1][y1]!='#'&&x1>0&&x1<=n&&y1>0&&y1<=m) { dir=(i+3)%4; dfs2(x1,y1,dir,step+1); } if(i==3) i-=4; } } void bfs(int sx,int sy) { int b=0,e=0,i; q[e++]=node(sx,sy); vis[sx][sy]=1; shortest[sx][sy]=1; while(b<e) { if(q[b].x==e1&&q[b].y==e2) { printf(" %d ",shortest[e1][e2]); break; } node now=q[b++]; for(i=0;i<4;i++) { int x1=now.x+xx[i]; int y1=now.y+yy[i]; if(x1>0&&x1<=n&&y1>0&&y1<=m&&!vis[x1][y1]&&mm[x1][y1]!='#') { vis[x1][y1]=1; shortest[x1][y1]=shortest[now.x][now.y]+1; q[e++]=node(x1,y1); } } } } int main() { int t,len; scanf("%d",&t); while(t--) { memset(mm,0,sizeof(mm)); scanf("%d%d",&m,&n); for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { scanf(" %c",&mm[i][j]); if(mm[i][j]=='S') s1=i,s2=j; if(mm[i][j]=='E') e1=i,e2=j; } } flag=0; dfs1(s1,s2,0,1); flag=0; dfs2(s1,s2,0,1); memset(vis,0,sizeof(vis)); bfs(s1,s2); } return 0; }