POJ1573Robot Motion

转载请注明出处:優YoU  http://user.qzone.qq.com/289065406/blog/1299128074

 

提示:不多说了,又是模拟题,读懂题意直接模拟就可以了,没有算法,没有技术含量,直接贴代码

 

 1 //Memory Time 
2 //256K 0MS
3
4
5 #include<iostream>
6 using namespace std;
7
8 int main(void)
9 {
10 int row,col,entry;
11 char grid[12][12]; //在规定大小的grid外部至少再定义一圈"门槛"以判断Robot是否离开了grid (最大grid为10x10)
12
13 for(;;)
14 {
15 memset(grid,'O',sizeof(grid)); // 'O' 为大写字母O,意为 Out
16
17 /*Input*/
18
19 int i,j;
20
21 cin>>row>>col>>entry;
22 if(!(row && col && entry))break;
23
24 for(i=1;i<=row;i++)
25 for(j=1;j<=col;j++)
26 cin>>grid[i][j];
27
28 /*Judge Robot get out of the grid or starts a loop in the grid*/
29
30 int flag[12][12]={0}; //标记Robot经过某点的次数,当有一点为2则说明Robot陷入了以该点为loop起始点的循环
31 int count;
32 int r=1;
33 int c=entry;
34 for(count=0;;count++)
35 {
36 flag[r][c]++; //注意顺序,先标记,再位移
37 if(grid[r][c]=='N') //
38 r--;
39 else if(grid[r][c]=='S') //
40 r++;
41 else if(grid[r][c]=='W') //
42 c--;
43 else if(grid[r][c]=='E') //
44 c++;
45 else if(grid[r][c]=='O') // Out
46 {
47 cout<<count<<" step(s) to exit"<<endl;
48 break;
49 }
50
51 if(flag[r][c]==2) //loop
52 {
53 row=r; //标记Robot循环起止点
54 col=c;
55 int flg=1;
56 for(r=1,c=entry,count=0;;count++)
57 {
58 if(r==row && c==col && flg==1) //注意顺序,先寻找循环点再位移(避免Robot刚进入grid就陷入了循环的情况)
59 {
60 cout<<count<<" step(s) before a loop of "; //输出进入循环前的步数
61 count=0;
62 flg++;
63 }
64 if(r==row && c==col && count!=0 && flg==2)
65 {
66 cout<<count<<" step(s)"<<endl; //输出循环步数
67 break;
68 }
69 if(grid[r][c]=='N') //
70 r--;
71 else if(grid[r][c]=='S') //
72 r++;
73 else if(grid[r][c]=='W') //
74 c--;
75 else if(grid[r][c]=='E') //
76 c++;
77 }
78 break; //跳出count的for循环,不是跳出if(当然break也不能用于跳出if,这里的说明是为了避免误解)
79 }
80 }
81 }
82 return 0;
83 }
原文地址:https://www.cnblogs.com/lyy289065406/p/2121386.html