Chinaunix首页 | 论坛 | 博客
  • 博客访问: 474207
  • 博文数量: 59
  • 博客积分: 345
  • 博客等级: 二等列兵
  • 技术积分: 1380
  • 用 户 组: 普通用户
  • 注册时间: 2011-06-18 22:44
个人简介

to be myself

文章分类

全部博文(59)

文章存档

2017年(5)

2013年(47)

2012年(3)

2011年(4)

分类: C/C++

2013-03-02 18:21:16


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <string.h>

  3. char ins[10][10]; //指令数组
  4. int vis[10][10]; //标记已访问坐标
  5. int fa[10][10]; //移到双亲坐标的指令

  6. int main()
  7. {
  8.        int r, c, s, i, x, y, step, tstep, j, lx, ly, tx, ty,
  9.               off[4][2]={0,1, 1,0, 0,-1, -1,0};//四个方向的偏移量
  10.        while(scanf("%d%d%d", &r, &c, &s) && (r || c || s))
  11.        {
  12.               memset(vis, 0, sizeof(vis));
  13.               memset(fa, 0, sizeof(fa));
  14.               for (i=0; i<r; i++)
  15.               {
  16.                      scanf("%s", ins[i]);
  17.               }
  18.               y = --s; //起始column标量和数组column相差1
  19.               x = 0;
  20.               step = 0;
  21.               while(1)
  22.               {
  23.                      if (x >= r || x < 0 || y >= c || y < 0) //数组越界,即robot已经exit
  24.                      {
  25.                             printf("%d step(s) to exitn", step);
  26.                             break;
  27.                      }
  28.                      step++;
  29.                      vis[x][y] = 1;
  30.                      switch(ins[x][y])
  31.                      { //四个ESWN方向分别定义为0123
  32.                             case 'E': j = 0; break;
  33.                             case 'S': j = 1; break;
  34.                             case 'W': j = 2; break;
  35.                             case 'N': j = 3; break;
  36.                      }
  37.                      if (vis[x+off[j][0]][y+off[j][1]]) //如果又走到了访问过的点,则有loop
  38.                      {
  39.                             tstep = step; //记录loop一圈后总共的步数
  40.                             lx = x + off[j][0];
  41.                             ly = y + off[j][1];
  42.                             while(!(x+off[fa[x][y]][0]==lx && y+off[fa[x][y]][1]==ly)) //根据fa数组倒退
  43.                             {
  44.                                    tx = off[fa[x][y]][0];
  45.                                    ty = off[fa[x][y]][1];
  46.                                    x += tx;
  47.                                    y += ty;
  48.                                    step--;
  49.                             }
  50.                             step -= 2; //多记了两个step减去.
  51.                             printf("%d step(s) before a loop of %d step(s)n", step, tstep-step);
  52.                             break;
  53.                      }
  54.                      x += off[j][0];
  55.                      y += off[j][1];
  56.                      fa[x][y] = (j + 2) % 4; //相反方向的回溯
  57.               }
  58.        }
  59.        return 0;
  60. }
2011-04-07 15:33 发表于百度空间,今搬至CU。
阅读(1527) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~