Robot Motion

来源:互联网 发布:2016三毛淘宝小号网址 编辑:程序博客网 时间:2024/05/23 05:08

Problem 78 » Robot Motion 查看标程

Description

Robot <wbr>Motion

A robot has been programmed to follow the instructions in its path.Instructions for the next direction the robot is to move are laiddown 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 ofGrid 1 and starts south (down). The path the robot follows isshown. The robot goes through 10 instructions in the grid beforeleaving the grid.

Compare what happens in Grid 2: the robot goes through 3instructions only once, and then starts a loop through 8instructions, and never exits.

You are to write a program that determines how long it takes arobot to get out of the grid or how the robot loopsaround.

INPUT

Therewill be one or more grids for robots to navigate. The data for eachis in the following form. On the first line are three integersseparated by blanks: the number of rows in the grid, the number ofcolumns in the grid, and the number of the column in which therobot enters from the north. The possible entry columns arenumbered starting with one at the left. Then come the rows of thedirection instructions. Each grid will have at least one and atmost 10 rows and columns of instructions. The lines of instructionscontain only the characters N, S, E, or W with no blanks. The endof input is indicated by a row containing 0 0 0.

OUTPUT

Foreach grid in the input there is one line of output. Either therobot follows a certain number of instructions and exits the gridon any one the four sides or else the robot follows theinstructions on a certain number of locations once, and then theinstructions on some number of locations repeatedly. The sampleinput below corresponds to the two grids above and illustrates thetwo forms of output. The word "step" is always immediately followedby "(s)" whether or not the number before it is 1.

SAMPLE INPUT

3 6 5NEESWEWWWESSSNWWWW4 5 1SESWEEESNWNWEENEWSEN0 0 

SAMPLE OUTPUT

10 step(s) to exit3 step(s) before a loop of 8 step(s)

HINT



模拟题目!!

#include<iostream>
using namespace std;
int w,h,t,mark[11][11],s;
char map[11][11];
void bfs(int x,int y)
{
 if(x<0||x>=h||y<0||y>=w)
 {
  cout<<s-1<<"step(s) to exit"<<endl;
  return ;
 }
 if(!mark[x][y])
  mark[x][y]=s++;
 else
 {
 cout<<mark[x][y]-1<<"step(s) before a loop of"<<s-mark[x][y]<<"step(s)"<<endl;
  return ;
 }
 if(map[x][y]=='W')
  bfs(x,y-1);
 else if(map[x][y]=='E')
    bfs(x,y+1);
 else if(map[x][y]=='S')
  bfs(x+1,y);
 else if(map[x][y]=='N')
  bfs(x-1,y);
}
int main()
{
   int i,j;
  while(cin>>h>>w&&h&&w)
   {
   cin>>t;
   s=1;
  memset(mark,0,sizeof(mark));
     for(i=0;i<h;i++)
   for(j=0;j<w;j++)
             cin>>map[i][j];
   bfs(0,t-1);
   }

}

0 0