Link:点击打开链接
Problem:
Robot Motion
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 6675 Accepted Submission(s): 3111

A robot has been programmed to follow the instructions in its path. Instructions for the next direction the robot is to move are laid down in a grid. The possible instructions are
N north (up the page)
S south (down the page)
E east (to the right on the page)
W west (to the left on the page)
For example, suppose the robot starts on the north (top) side of Grid 1 and starts south (down). The path the robot follows is shown. The robot goes through 10 instructions in the grid before leaving the grid.
Compare what happens in Grid 2: the robot goes through 3 instructions only once, and then starts a loop through 8 instructions, and never exits.
You are to write a program that determines how long it takes a robot to get out of the grid or how the robot loops around.
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<stdio.h>
#include<string.h>
char map[22][33];
int vis[22][33],sp[22][33];
int m[22][33];
int d[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int n,k,ans1,ans2;
void dfs(int r,int c,int dir)
{
if(r>=n||r<0||c<0||c>=k)
{
r-=d[dir][0];
c-=d[dir][1];
ans1=sp[r][c]+1;
return;
}
if(vis[r][c])
{
ans1=sp[r][c];
r-=d[dir][0];
c-=d[dir][1];
ans2=sp[r][c]+1-ans1;
return;
}
vis[r][c]=1;
sp[r][c]=sp[r-d[dir][0]][c-d[dir][1]]+1;
dfs(r+d[m[r][c]][0],c+d[m[r][c]][1],m[r][c]);
}
int main()
{
int i,j,x;
while(scanf("%d%d",&n,&k)!=EOF&&n&&m)
{
scanf("%d",&x);
for(i=0;i<n;i++)
{
scanf("%s",map[i]);
for(j=0;j<k;j++)
{
if(map[i][j]=='E')
m[i][j]=0;
if(map[i][j]=='W')
m[i][j]=1;
if(map[i][j]=='S')
m[i][j]=2;
if(map[i][j]=='N')
m[i][j]=3;
}
}
memset(vis,0,sizeof(vis));
vis[0][x-1]=1;
sp[0][x-1]=0;
ans1=ans2=0;
dfs(0+d[m[0][x-1]][0],x-1+d[m[0][x-1]][1],m[0][x-1]);
if(ans2==0)
{
// if(ans1==1)
// printf("%d step to exit\n",ans1);
// else
printf("%d step(s) to exit\n",ans1);
}
else
{
// if(ans1==1)
// printf("%d step before a loop of %d step(s)\n",ans1,ans2);
// else
printf("%d step(s) before a loop of %d step(s)\n",ans1,ans2);
}
}
return 0;
}