Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7974 Accepted Submission(s):
3685
#include<stdio.h> #include<string.h> #define MAX 110 char map[MAX][MAX];//所要走的地图 int vis[MAX][MAX];//用来记录当前走了多少步 int n,m,t; int x2,y2;//用于记录当前步的上一步 void dfs(int x1,int y1) { if(x1>n||x1<1||y1<1||y1>m)//如果超出地图范围则证明已经走出去了 { printf("%d step(s) to exit\n",vis[x2][y2]); return ; } else if(vis[x1][y1])//如果不为0则证明此处已经走过形成环 { printf("%d step(s) before a loop of %d step(s)\n",vis[x1][y1]-1,vis[x2][y2]-vis[x1][y1]+1); return ; } vis[x1][y1]=vis[x2][y2]+1;//当前走的步数是上一步加1 x2=x1;y2=y1; if(map[x1][y1]==‘W‘)//向左走 y1-=1; else if(map[x1][y1]==‘S‘)//向下走 x1+=1; else if(map[x1][y1]==‘E‘)//向右走 y1+=1; else if(map[x1][y1]==‘N‘)//向上走 x1-=1; dfs(x1,y1); } int main() { int j,i,s,k; int x1,x2,y1,y2; while(scanf("%d%d",&n,&m)&&n!=0&&m!=0) { scanf("%d",&t); for(i=1;i<=n;i++) { getchar(); for(j=1;j<=m;j++) { scanf("%c",&map[i][j]); } } x1=1;y1=t;//起点 x2=x1;y2=y1; memset(vis,0,sizeof(vis));//数组清零 dfs(x1,y1); } return 0; }
原文:http://www.cnblogs.com/tonghao/p/4614739.html