题目地址:http://poj.org/problem?id=1573
1 /*
2 题意:给定地图和起始位置,robot(上下左右)一步一步去走,问走出地图的步数
3 如果是死循环,输出走进死循环之前的步数和死循环的步数
4 模拟题:used记录走过的点,因为路线定死了,所以不是死循环的路只会走一次,可以区分出两个步数
5
6 注意:比较坑的是,如果不是死循环,临界(走进去就出来)步数是1;而死循环却是0. 这里WA几次。。。
7 */
8 #include <cstdio>
9 #include <iostream>
10 #include <algorithm>
11 #include <cstring>
12 #include <cmath>
13 #include <string>
14 #include <map>
15 #include <queue>
16 #include <vector>
17 using namespace std;
18
19 const int MAXN = 20;
20 const int INF = 0x3f3f3f3f;
21 int a[MAXN][MAXN];
22 int used[MAXN][MAXN];
23
24 void work(int n, int m, int k)
25 {
26 int ans = 0; int cnt = 0; int i = 1, j = k;
27 while (i >= 1 && i <= n && j >= 1 && j <= m)
28 {
29 if (used[i][j] <= 2)
30 {
31 switch (a[i][j])
32 {
33 case 'N': i -= 1; break;
34 case 'S': i += 1; break;
35 case 'W': j -= 1; break;
36 case 'E': j += 1; break;
37 }
38 used[i][j]++;
39 if (used[i][j] == 2) cnt++;
40 else ans++;
41 }
42 else
43 {
44 int res = ans - cnt;
45 if (res == 1) res = 0;
46 printf ("%d step(s) before a loop of %d step(s)
", res, cnt);
47 break;
48 }
49 }
50 if (i < 1 || i > n || j < 1 || j > m)
51 printf ("%d step(s) to exit
", ans);
52 }
53
54 int main(void) //POJ 1573 Robot Motion
55 {
56 //freopen ("H.in", "r", stdin);
57
58 int n, m, k;
59 while (~scanf ("%d%d%d", &n, &m, &k) && n && m && k)
60 {
61 getchar ();
62 for (int i=1; i<=n; ++i)
63 {
64 for (int j=1; j<=m; ++j)
65 {
66 a[i][j] = getchar ();
67 }
68 getchar ();
69 }
70
71 memset (used, 0, sizeof (used));
72 work (n, m, k);
73 }
74
75 return 0;
76 }
77
78 /*
79 10 step(s) to exit
80 3 step(s) before a loop of 8 step(s)
81 */