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>
#include<algorithm>
#include<string>
#include<cstring>
#include<stdio.h>
#include<cmath>
using namespace std;
int x,y,start;
struct Nod{
char str;
bool visited;
int Long;
} array[11][11];
int step,loops,flag,before_step;
void DFS(int i,int j)
{
if(flag == 1 || flag == 2)
{
return;
}
if((i == 0 && array[i][j].str == 'N')||(j == 0 && array[i][j].str == 'W')||
(i == x - 1 && array[i][j].str == 'S')||(j == y - 1 && array[i][j].str == 'E'))
{
flag = 1;
return;
}
if(array[i][j].visited == true)
{
loops = step - array[i][j].Long + 1;
before_step = array[i][j].Long - 1;
flag = 2;
return;
}
else if(array[i][j].visited == false)
{
if(array[i][j].str == 'E')
{
step++;
array[i][j].Long = step;
array[i][j].visited = true;
DFS(i,j + 1);
}
else if(array[i][j].str == 'W')
{
step++;
array[i][j].Long = step;
array[i][j].visited = true;
DFS(i,j- 1);
}
else if(array[i][j].str == 'N')
{
step++;
array[i][j].Long = step;
array[i][j].visited = true;
DFS(i - 1,j);
}
else if(array[i][j].str == 'S')
{
step++;
array[i][j].Long = step;
array[i][j].visited = true;
DFS(i + 1,j);
}
}
}
int main()
{
int i,j,k;
while(~scanf("%d%d%d",&x,&y,&start))
{
if(x == 0&&y == 0&&start == 0)
break;
flag = 0;
step = 0;
for(i = 0;i < x;i++)
{
for(j = 0;j < y;j++)
{
cin>>array[i][j].str;
array[i][j].visited = false;
array[i][j].Long = 0;
}
}
DFS(0, start- 1);
if(flag == 1)
{
cout<<step + 1<<" step(s) to exit"<<endl;
}
else if(flag == 2)
{
cout<<before_step<<" step(s) before a loop of "<<loops<<" step(s)"<<endl;
}
}
return 0;
}