
3 6 5 NEESWE WWWESS SNWWWW 4 5 1 SESWE EESNW NWEEN EWSEN 0 0
10 step(s) to exit 3 step(s) before a loop of 8 step(s)
#include<iostream>
#include<cstring>
using namespace std;
char ch[105][105];
int ans;
int v[105][105],w[105][105];
int a,b,c,t;
void dfs(int x,int y)
{
if(t==1) return ;
v[x][y]=1;
ans++;
if(ch[x][y]=='N') x-=1;
else if(ch[x][y]=='E') y+=1;
else if(ch[x][y]=='S') x+=1;
else if(ch[x][y]=='W') y-=1;
if(x<0||y<0||x>=a||y>=b)
{
t=1;
printf("%d step(s) to exit\n",ans);
return ;
}
else if(v[x][y])
{
t=1;
printf("%d step(s) before a loop of %d step(s)\n",w[x][y],ans-w[x][y]);
return ;
}
w[x][y]=ans;
if(!v[x][y])
dfs(x,y);
}
int main()
{
while(cin>>a>>b>>c)
{
if(a==0||b==0||c==0) break;
t=0;
int i,j;
for(i=0;i<a;i++)
scanf("%s",ch[i]);
memset(v,0,sizeof(v));
ans=0;
for(i=0;i<a;i++)
for(j=0;j<b;j++)
{
if(j==c-1)
{
dfs(i,j);
}
}
}
return 0;
}原文地址:http://blog.csdn.net/hyccfy/article/details/37967915