POJ1573(Robot Motion)

题目大意:

     给你一个布满N/W/E/S的矩阵。 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) 。机器人从给出的第一行的某个位置进入矩阵,看机器人能否出去矩阵输出多少步数,或者在某个位置形成回路输出进入回路前的步数和回路的步数。

 

解题思路:

   简单模拟,用一个cas标识符记录机器人的步数,使机器人走过的路径清为‘0’  。如下次遇见‘0’,说明访问过。 然后return即可。还需要一个数组记录该位置走过时的步数。

 

代码:

 

  1 #include <algorithm>
  2 #include <iostream>
  3 #include <sstream>
  4 #include <cstdlib>
  5 #include <cstring>
  6 #include <cstdio>
  7 #include <string>
  8 #include <bitset>
  9 #include <vector>
 10 #include <queue>
 11 #include <stack>
 12 #include <cmath>
 13 #include <list>
 14 #include <map>
 15 #include <set>
 16 using namespace std;
 17 /***************************************/
 18 #define ll long long
 19 #define int64 __int64
 20 /***************************************/
 21 const int INF = 0x7f7f7f7f;
 22 const double eps = 1e-8;
 23 const double PIE=acos(-1.0);
 24 const int dx[]= {0,-1,0,1};
 25 const int dy[]= {1,0,-1,0};
 26 const int fx[]= {-1,-1,-1,0,0,1,1,1};
 27 const int fy[]= {-1,0,1,-1,1,-1,0,1};
 28 /***************************************/
 29 void openfile()
 30 {
 31     freopen("data.in","rb",stdin);
 32     freopen("data.out","wb",stdout);
 33 }
 34 /**********************华丽丽的分割线,以上为模板部分*****************/
 35 int b[100][100],cas,flag,x1;
 36 int yy;
 37 char a[100][100];
 38 int m,n;
 39 void DFS(int x,int y)
 40 {
 41     if (x<0||x>=m||y<0||y>=n)
 42         return ;
 43     if (a[x][y]=='0')
 44     {
 45         flag=1;
 46         x1=x;
 47         yy=y;
 48         return ;
 49     }
 50     if (a[x][y]=='N')
 51     {
 52         cas++;
 53         b[x][y]=cas;
 54         a[x][y]='0';
 55         x1=x;
 56         yy=y;
 57         DFS(x-1,y);
 58     }
 59     if (a[x][y]=='S')
 60     {
 61         cas++;
 62         b[x][y]=cas;
 63         a[x][y]='0';
 64         x1=x;
 65         yy=y;
 66         DFS(x+1,y);
 67     }
 68     if (a[x][y]=='E')
 69     {
 70         cas++;
 71         b[x][y]=cas;
 72         a[x][y]='0';
 73         x1=x;
 74         yy=y;
 75         DFS(x,y+1);
 76     }
 77     if (a[x][y]=='W')
 78     {
 79         cas++;
 80         b[x][y]=cas;
 81         a[x][y]='0';
 82         x1=x;
 83         yy=y;
 84         DFS(x,y-1);
 85     }
 86 }
 87 int main()
 88 {
 89     while(scanf("%d%d",&m,&n)&&m&&n)
 90     {
 91         int w,i,j;
 92         scanf("%d",&w);
 93         for(i=0;i<m;i++)
 94             scanf("%s",a[i]);
 95         flag=0;
 96         cas=0;
 97         memset(b,0,sizeof(b));
 98         DFS(0,w-1);
 99         if (flag)
100             printf("%d step(s) before a loop of %d step(s)\n",b[x1][yy]-1,cas-b[x1][yy]+1);
101         else
102             printf("%d step(s) to exit\n",b[x1][yy]);
103     }
104     return 0;
105 }
View Code

 

posted @ 2014-05-28 16:30  kinghold  Views(187)  Comments(0Edit  收藏  举报