题意就是输入n*m的地图,然后输入p,表示这个机器人从(1,p)这个点为起点,然后至于机器人怎么走应该不用解释了吧,判断的终点就是走出地图,这里我们可以稍稍的做个预处理,地图从1开始输入,那么结束条件就是到达0,n+1,m+1就行了。把字母换成数字存起来,然后每走过一个点都用走的步数标记,当如果走到了标记过的点就说明存在一个环,然后此时的步数就是第一次走到这个点所用的步数,因为用step记录了总步数,所以减一下就是环的长度了。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MAXN = 1005;
int MAP[MAXN][MAXN];
int vis[MAXN][MAXN];
int n,m,p,flag,ans,temp;
char ch;
void dfs(int x,int y,int step){
if(flag)return ;
int X,Y;
if(MAP[x][y] == 1){
X = x - 1;
Y = y;
}
else if(MAP[x][y] == 2){
X = x + 1;
Y = y;
}
else if(MAP[x][y] == 3){
X = x;
Y = y - 1;
}
else {
X = x;
Y = y + 1;
}
if(X == 0 || Y == 0 || X == n+1 || Y == m+1){
flag = 1;
printf("%d step(s) to exit\n",vis[x][y]);
return ;
}
if(vis[X][Y]){
flag = 1;
printf("%d step(s) before a loop of %d step(s)\n",vis[X][Y] - 1,step+ 1 - vis[X][Y]);
ans = step + 1 - vis[X][Y];
temp = vis[X][Y] - 1;
return ;
}
vis[X][Y] = vis[x][y] + 1;
dfs(X,Y,vis[X][Y]);
}
int main()
{
while(~scanf("%d%d",&n,&m)){
flag = 0;
if(n == 0 && m == 0) break;
scanf("%d",&p);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
vis[i][j] = 0;
cin>>ch;
if(ch == 'N'){
MAP[i][j] = 1;
}
else if(ch == 'S'){
MAP[i][j] = 2;
}
else if(ch == 'W'){
MAP[i][j] = 3;
}
else {
MAP[i][j] = 4;
}
}
}
vis[1][p] = 1;
dfs(1,p,0);
}
return 0;
}