MP [r] [C] [0] Save the direction of (R, C) on the map
As follows:
N (8)
W (4) E (6)
S (2)
Number of times the MP [r] [C] [1] storage point (R, c) has passed
When the third encounter (R, c ),
Otherwise, MP [r] [C] [1] ++
#include<iostream>using namespace std;int main(){int mp[12][12][4],r,c,e,x,y,nloop,nstep,i,j;char t;while(scanf("%d%d%d",&r,&c,&e)&&(r||c||e)){memset(mp,0,sizeof(mp));for(i=1;i<=r;i++){getchar();for(j=1;j<=c;j++){scanf("%c",&t);if(t=='E') mp[i][j][0]=6;else if(t=='S') mp[i][j][0]=2; else if(t=='W') mp[i][j][0]=4; else mp[i][j][0]=8;}}nstep=nloop=0;x=e;y=1;while(1){if(mp[y][x][1]==2||y>r||y<1||x>c||x<1) break;if(mp[y][x][1]==0) nstep++;else nloop++;mp[y][x][1]++;if(mp[y][x][0]==2) y++;else if(mp[y][x][0]==8) y--; else if(mp[y][x][0]==4) x--; else x++;}if(nloop==0)printf("%d step(s) to exit\n",nstep);elseprintf("%d step(s) before a loop of %d step(s)\n",nstep-nloop,nloop);}return 0;}