HDU-1035-Robot Motion(开两个数组简单模拟,话说最近一直再做模拟......C++)
Robot Motion
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 7825 Accepted Submission(s): 3582
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)
#include<iostream> #include<cstdio> #include<cstring> using namespace std; char map[20][20]; //存取地图 int step[20][20]; //记录当前走的总步数 int n,m,start; bool is_inmap(int x,int y) //判断是否走出边界了 { if(!(x>=0&&y>=0&&x<n&&y<m)) { return false; } else { return true; } } int main() { while(scanf("%d%d",&n,&m)&&n) { scanf("%d",&start); memset(map,0,sizeof(map)); memset(step,-1,sizeof(step)); //这里把数组里面每一个值设置为-1 for(int i=0;i<n;i++) scanf("%s",map[i]); int AnsSteps = 0; //用来存取走的总步数 step[0][start-1]=0; int x=0,y=start-1; //记录起点的坐标 while(1) { if(map[x][y]=='N') { x--; } else if(map[x][y]=='S') { x++; } else if(map[x][y]=='E') { y++; } else if(map[x][y]=='W') { y--; } AnsSteps++; if(!is_inmap(x,y)) //是否还在地图当中 { printf("%d step(s) to exit\n",AnsSteps); break; } if(step[x][y]==-1) //step[x][y]等于-1说明当前点没有走过则换成AnsSteps step[x][y]=AnsSteps; else //否则已经访问过,有死循环,输出 { printf("%d step(s) before a loop of %d step(s)\n",step[x][y],AnsSteps-step[x][y]); break; } } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。