Robot Motion
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 33 Accepted Submission(s) : 16
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
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.
Input
Output
Sample Input
3 6 5 NEESWE WWWESS SNWWWW 4 5 1 SESWE EESNW NWEEN EWSEN 0 0
Sample Output
10 step(s) to exit 3 step(s) before a loop of 8 step(s)
#include <iostream>
#include <string>#include <stdio.h>
using namespace std;
char a[12][12];
int b[1100][1100];
int i,j,m,n,k,step;
void DFS (int x,int y)
{
while (x>=0&&x<m&&y>=0&&y<n&&a[x][y]!='0')
{
if (a[x][y]=='N')
{
a[x][y]='0';
b[x][y]=step++;
x--;
}
else if(a[x][y]=='W')
{
a[x][y]='0';
b[x][y]=step++;
y--;
}
else if(a[x][y]=='S')
{
a[x][y]='0';
b[x][y]=step++;
x++;
}
else if(a[x][y]=='E')
{
a[x][y]='0';
b[x][y]=step++;
y++;
}
}
if(a[x][y]=='0')
printf("%d step(s) before a loop of %d step(s)\n",b[x][y],step-b[x][y]);
else
printf("%d step(s) to exit\n",step);
}
int main ()
{
int p,q;
while (scanf("%d%d%d",&m,&n,&k)!=EOF)
{
if (m==0||n==0)
break;
for (i=0;i<m;i++)
scanf("%s",&a[i]);
p=0;
q=k-1;
step=0;
DFS(p,q);
}
return 0;
}
另外一种解法 只用一个循环就可以解决:
#include <stdio.h>
#include <string.h>
#define N 505
#define M 505
int b[N][M];
char map1[N][M];
int main ()
{ int n,m,t,x,y,x1,y1,i,e[150][2];
memset (e,0,sizeof(e));
e['N'][0]=-1;e['N'][1]=0;
e['S'][0]=1;e['S'][1]=0;
e['E'][0]=0;e['E'][1]=1;
e['W'][0]=0;e['W'][1]=-1;
while (scanf("%d%d",&n,&m),n||m)
{
memset (b,-1,sizeof(b));
scanf("%d",&t);
getchar();
for(i=0;i<n;i++)
scanf("%s",map1[i]);
for(x=0,y=t-1,i=0;x>=0&&x<n&&y>=0&&y<m&&b[x][y]==-1;i++)
{
b[x][y]=i;
x1=x;y1=y;
x+=e[map1[x1][y1]][0];
y+=e[map1[x1][y1]][1];
}
if(x>=0&&x<n&&y>=0&&y<m)
printf("%d step(s) before a loop of %d step(s)\n",b[x][y],i-b[x][y]);
else
printf("%d step(s) to exit\n",i);
}
return 0;
}