Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 12856 | Accepted: 6240 |
Descriptionios
Input數組
Outputapp
Sample Inputide
3 6 5 NEESWE WWWESS SNWWWW 4 5 1 SESWE EESNW NWEEN EWSEN 0 0 0
Sample Outputoop
10 step(s) to exit 3 step(s) before a loop of 8 step(s)
Sourcethis
題目連接:POJ 1573spa
簡單BFS,過不了的是試一下這組樣例……orm
Try this test case: 2 2 1 SW EN The right answer should be: 0 step(s) before a loop of 4 step(s)
因爲剛開始的步數爲0,加了一個vis數組,用一個數組記錄每一次到的地方的步數便可,若訪問過就說明有迴路,若能夠走出界則說明有出口……blog
代碼:three
#include<iostream> #include<algorithm> #include<cstdlib> #include<sstream> #include<cstring> #include<bitset> #include<cstdio> #include<string> #include<deque> #include<stack> #include<cmath> #include<queue> #include<set> #include<map> using namespace std; #define INF 0x3f3f3f3f #define CLR(x,y) memset(x,y,sizeof(x)) #define LC(x) (x<<1) #define RC(x) ((x<<1)+1) #define MID(x,y) ((x+y)>>1) typedef pair<int,int> pii; typedef long long LL; const double PI=acos(-1.0); const int N=15; char pos[N][N]; int his_step[N][N]; int vis[N][N]; struct info { int x; int y; int step; info operator+(info b) { b.x+=x; b.y+=y; b.step+=step; return b; } }; info S,direct[4]={{0,1,1},{0,-1,1},{1,0,1},{-1,0,1}}; int n,m,c; void init() { CLR(pos,0); CLR(his_step,0); CLR(vis,0); } int main(void) { int i,j,k,ans1,ans2; while (~scanf("%d%d%d",&n,&m,&c)&&(n||m||c)) { init(); ans1=-1; ans2=-1; for (i=0; i<n; ++i) scanf("%s",pos[i]); S.x=0; S.y=c-1; S.step=0; queue<info>Q; Q.push(S); while (!Q.empty()) { info now=Q.front(); Q.pop(); if(vis[now.x][now.y]) { ans1=his_step[now.x][now.y]; ans2=now.step-his_step[now.x][now.y]; break; } else { his_step[now.x][now.y]=now.step; vis[now.x][now.y]=1; } info v; switch(pos[now.x][now.y]) { case 'N':v=now+direct[3];break; case 'S':v=now+direct[2];break; case 'W':v=now+direct[1];break; case 'E':v=now+direct[0];break; } if(v.x<0||v.x>=n||v.y<0||v.y>=m) { ans1=v.step; break; } Q.push(v); } if(ans2==-1) printf("%d step(s) to exit\n",ans1); else printf("%d step(s) before a loop of %d step(s)\n",ans1,ans2); } return 0; }