BNUOJ 4358 左手定则 搜索

题目链接:http://acm.bnu.edu.cn/bnuoj/problem_show.php?pid=4358

一道很好的搜索题,要注意DFS函数的写法,特别是return的写法。

View Code
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 char map[105][105];
 6 int a[105][105][4];
 7 int sx,sy,tx,ty,flag,n,m;
 8 int px[4][4]=
 9 {
10     0,-1,0,1,
11         0,1,0,-1,
12         1,0,-1,0,
13         -1,0,1,0
14 };
15 int py[4][4]=
16 {
17     -1,0,1,0,
18         1,0,-1,0,
19         0,-1,0,1,
20         0,1,0,-1
21 };
22 int f[4][4]=
23 {
24     2,0,3,1,
25         3,1,2,0,
26         1,2,0,3,
27         0,3,1,2
28 };
29 void DFS(int x,int y,int v)
30 {
31     int i,xx,yy,tv;
32     if(flag)return ;
33     if(x==tx&&y==ty)
34     {
35         flag=1;
36         return ;
37     }
38     for(i=0;i<4;i++)
39     {
40         xx=x+px[v][i];
41         yy=y+py[v][i];
42         if(xx<1||xx>n||yy<1||yy>m||map[xx][yy]=='#')continue ;
43         tv=f[v][i];
44         if(a[xx][yy][tv]==-1)
45         {
46             a[xx][yy][tv]=1;
47             DFS(xx,yy,tv);
48         }
49         return ;
50     }
51 }
52 int main()
53 {
54     int i,j,v;
55     char ch;
56     while(scanf("%d%d",&n,&m)!=EOF)
57     {
58         
59         for(i=1;i<=n;i++)
60             for(j=1;j<=m;j++)
61             {
62                 //scanf("%c",&map[i][j]);
63                 cin>>map[i][j];
64                 if(map[i][j]=='S')
65                 {
66                     sx=i;
67                     sy=j;
68                     
69                 }
70                 if(map[i][j]=='T')
71                 {
72                     tx=i;
73                     ty=j;
74                 }
75             }
76        cin>>ch;
77         //    scanf("%c",&ch);
78             if(ch=='N')v=0;
79             else if(ch=='S')v=1;
80             else if(ch=='W')v=2;
81             else v=3;
82             flag=0;
83             memset(a,-1,sizeof(a));
84             a[sx][sy][v]=1;
85             DFS(sx,sy,v);
86             if(flag)printf("YES\n");
87             else printf("NO\n");
88     }
89     return 0;
90 }
posted @ 2012-04-16 17:26  我们一直在努力  阅读(257)  评论(0编辑  收藏  举报