Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10564 | Accepted: 4539 |
Description
Input
Output
Sample Input
2 8 8 ######## #......# #.####.# #.####.# #.####.# #.####.# #...#..# #S#E#### 9 5 ######### #.#.#.#.# S.......E #.#.#.#.# #########
Sample Output
37 5 5 17 17 9
题意:从迷宫起点S到终点E,分别求沿左边的墙走的步数,沿右边墙走的步数,最短路的步数;
思路:最短路直接bfs,沿着墙走dfs+模拟,每次递归时记录方向和并更改计算下一时刻的方向,按方向顺时针(或逆时针)走,注意取余;
难点:模拟。。。弄了3个多小时。。。
bfs还忘了改vis判重造成MLE。。。。模拟时还把左右方向弄反了。。。
唯一欣慰的是0秒过了。。。
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstdlib> #include<cstring> #include<algorithm> #include<map> #include<vector> #include<queue> using namespace std; const int maxn=43; int n,m; char ch[maxn][maxn]; bool vis[maxn][maxn]; int si,sj; int ei,ej; int stepL,stepR,stepS; struct node { int x,y; }; int dx[]={0,1,0,-1}; int dy[]={-1,0,1,0}; bool flag; void bfs(int si,int sj) { queue<node> q; q.push({si,sj}); int dist[maxn][maxn]; memset(dist,0,sizeof(dist)); dist[si][sj]=1; vis[si][sj]=1; while(!q.empty()){ node now=q.front(); q.pop(); for(int i=0;i<4;i++){ int nx=now.x+dx[i],ny=now.y+dy[i]; if(vis[nx][ny]||ch[nx][ny]=='#') continue; vis[nx][ny]=1; dist[nx][ny]=dist[now.x][now.y]+1; if(ch[nx][ny]=='E'){ stepS=dist[nx][ny]; return; } q.push({nx,ny}); } } } void dfs(int x,int y,char end,int dir,int step,bool tag) { if(flag) return; if(ch[x][y]==end){ if(tag) stepL=step; else stepR=step; flag=1;return; } for(int i=0;i<4;i++){ int nx=x+dx[(dir+i)%4],ny=y+dy[(dir+i)%4]; int ndir=(dir+i+3)%4; if(ch[nx][ny]=='#') continue; dfs(nx,ny,end,ndir,step+1,tag); } } int main() { int T;cin>>T; while(T--){ cin>>m>>n; stepL=stepR=stepS=0; memset(ch,'#',sizeof(ch)); for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cin>>ch[i][j]; if(ch[i][j]=='S'){ si=i;sj=j; } if(ch[i][j]=='E'){ ei=i;ej=j; } } } flag=0; dfs(si,sj,'E',0,1,1); flag=0; dfs(ei,ej,'S',0,1,0); memset(vis,0,sizeof(vis)); bfs(si,sj); cout<<stepR<<" "<<stepL<<" "<<stepS<<endl; } return 0; }