Robot Motion
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 5009 Accepted Submission(s): 2319
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)
简单的dfs搜索,但我还是感觉压力山大啊,总算过了。
#include<iostream>
using namespace std;
int N, M, Y, num_e, num_l;
struct node
{
int x;
char c;
bool visit;
}a[12][12];
void dfs(int x1,int y1)
{
int x,y;
switch(a[x1][y1].c)
{
case 'N':x=x1-1;y=y1;break;
case 'S':x=x1+1;y=y1;break;
case 'E':x=x1;y=y1+1;break;
case 'W':x=x1;y=y1-1;break;
}
if(x<1||x>N||y<1||y>M)
{
num_l=0;
num_e=a[x1][y1].x;
return ;
}
else if(a[x][y].visit==1)
{
num_e=a[x][y].x-1;
num_l=a[x1][y1].x-a[x][y].x+1;
return ;
}
else if(a[x][y].visit==0)
{
a[x][y].x=a[x1][y1].x+1;
a[x][y].visit=1;
dfs(x,y);
}
return ;
}
int main()
{
while(cin>>N>>M)
{
if(N==0&&M==0)
break;
cin>>Y;
if(N == 0 || M == 0 || Y == 0)
break;
for(int i=1;i<=N;i++)
for(int j=1;j<=M;j++)
{
cin>>a[i][j].c;
a[i][j].x = 0;
a[i][j].visit = 0;
}
a[1][Y].x=1;
a[1][Y].visit=1;
dfs(1,Y);
if(num_e != 0 && num_l == 0)
cout << num_e << " step(s) to exit" << endl;
if(num_l != 0)
cout << num_e << " step(s) before a loop of "
<< num_l << " step(s)" << endl;
}
return 0;
}