Robot Motion POJ - 1573
题目链接:https://vjudge.net/problem/POJ-1573
题意:一个机器人在大小为n行m列的方格图上行走。小方格上有各种指令:
N north (向上走一步)
S south (向下走一步)
E east (向右走一步)
W west (向左走一步)
机器人会根据指令行走,问:
机器人会走出地图还是会陷入死循环,如走出地图,问几步走出地图;如陷入死循环,问走几步陷入循环,循环的周期是多少。
思路:模拟这个过程,用dfs跑图即可。重点要记录vis[x][y]数组,用来表示到(x,y)所用的步数。vis[x][y]==0表示没走过,下次遇到vis[x][y]!=0的,用当前步数减去这个vis的值即为循环。这个vis的值本身即为几步进入死循环
代码:
#include<iostream>
#include<cstring>
using namespace std;
const int maxn=17;
char ma[maxn][maxn];
int vis[maxn][maxn];
int circle;
int out;
int steps;
int n,m;
void go(int x,int y,int tem){
//cout<<"this is "<<x<<" "<<y<<endl;
//vis
if(vis[x][y]==0)vis[x][y]=tem;
else{
//cout<<"cir\n";
circle=tem-vis[x][y];
steps=vis[x][y];
return ;
}
//move
char dir=ma[x][y];
int nx=x,ny=y;
if(dir=='N')nx=x-1;
else if(dir=='S')nx=x+1;
else if(dir=='W')ny=y-1;
else if(dir=='E')ny=y+1;
//cout<<nx<<" "<<ny<<endl;
if(nx>=1&&nx<=n&&ny>=1&&ny<=m)go(nx,ny,tem+1);
else{
//cout<<"out!\n";
out=tem;
}
}
int main(){
int s;
while(cin>>n>>m>>s){
memset(vis,0,sizeof(vis));
if(n==0&&m==0&&s==0)break;
int i,j;
circle=0;
for(i=1;i<=n;i++){
for(j=1;j<=m;j++){
cin>>ma[i][j];
}
}
go(1,s,1);
if(circle==0){//no circle
cout<<out<<" step(s) to exit\n";
}
else{
cout<<steps-1<<" step(s) before a loop of "<<circle<<" step(s)\n";
}
}
return 0;
}