Robot Motion--POJ 1573
1、题目类型:模拟。
2、解题思路:水题,模拟robotd的移动,并记录移动步数即可。
3、注意事项:在loop时候,注意结束条件。
4、实现方法:
#include<iostream>
using namespace std;
struct Node{
int step;
char dir;
};
Node map[15][15];
int s,row,col,ans,t;
bool flag;
void solution()
{
int i=1,j=s,p,q;
map[i][j].step=1;
while(i>0 &&i<=row &&j>0 &&j<=col)
{
p=i;
q=j;
switch(map[i][j].dir)
{
case 'E':
j++;
if(!map[i][j].step)
{
map[i][j].step=map[p][q].step+1;
}
else
{
flag=0;
ans=map[i][j].step-1;
t=map[p][q].step-map[i][j].step+1;
return;
}
break;
case 'N':
i--;
if(!map[i][j].step)
{
map[i][j].step=map[p][q].step+1;
}
else
{
flag=0;
ans=map[i][j].step-1;
t=map[p][q].step-map[i][j].step+1;
return;
}
break;
case 'W':
j--;
if(!map[i][j].step)
{
map[i][j].step=map[p][q].step+1;
}
else
{
flag=0;
ans=map[i][j].step-1;
t=map[p][q].step-map[i][j].step+1;
return;
}
break;
case 'S':
i++;
if(!map[i][j].step)
{
map[i][j].step=map[p][q].step+1;
}
else
{
flag=0;
ans=map[i][j].step-1;
t=map[p][q].step-map[i][j].step+1;
return;
}
break;
default:
break;
}
}
ans=map[p][q].step;
}
int main()
{
int i,j;
while(cin>>row>>col>>s && row || col || s)
{
flag=1;
ans=0;
memset(map,0,sizeof(map));
for(i=1;i<=row;i++)
{
getchar();
for(j=1;j<=col;j++)
{
scanf("%c",&map[i][j].dir);
}
}
solution();
if(flag)
cout<<ans<<" step(s) to exit"<<endl;
else
cout<<ans<<" step(s) before a loop of "<<t<<" step(s)"<<endl;
}
return 0;
}