题意:给定你一个迷宫,从起点走到终点,不能走重复的路,一定要在T步的时候走到终点

解题思路:奇偶判断+可到达判断

解题代码:

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include <math.h>
 5 int bex,bey,enx,eny; 
 6 int xadd[5] = {0,1,0,-1};
 7 int yadd[5] = {1,0,-1,0};
 8 int map[10][10];
 9 int n , m ,limit;
10 int ok = 0;
11 int visit[10][10];
12 int ABS(int x)
13 {
14   if(x <= 0 )
15       return -x;
16   else return x;
17 }
18 void dfs(int x, int y , int step)
19 {
20     //printf("%d %d %d %d %d\n",x,y,limit - step,ABS(enx-x), ABS(eny -y));
21     if(map[x][y] == 2 && step == limit)
22     {
23         ok = 1;
24         return ;
25     }
26    
27     if(ABS(enx-x) + ABS(eny -y) > limit - step)
28         return;
29     if(ok)
30         return;
31     for(int i = 0 ;i <= 3;i ++)
32     {
33         int tx =x + xadd[i];
34         int ty =y + yadd[i];
35         if(map[tx][ty] && !visit[tx][ty])
36         {
37           visit[tx][ty] = 1; 
38           dfs(tx,ty,step+1);
39           visit[tx][ty] = 0;
40         }
41 
42     }
43 }
44 int main()
45 {
46     while(scanf("%d %d %d",&n,&m,&limit)!=EOF, n)
47     {
48       memset(map,0,sizeof(map));
49       memset(visit,0,sizeof(visit));
50       ok = 0 ;
51       for(int i =1 ;i<= n;i ++)
52       {
53         char str[10];
54         scanf("%s",&str[1]);
55         for(int j =1;j <= m;j ++)
56         {
57           if(str[j] == 'S')
58           {
59               bex = i; 
60               bey = j; 
61               map[i][j] = 1 ;
62           }
63           else if(str[j] == 'D')
64           {
65               enx = i ; 
66               eny = j ; 
67               map[i][j] = 2;
68           }else if(str[j] == '.')
69               map[i][j] = 1; 
70           else map[i][j] = 0 ; 
71 
72         }
73 
74       }
75       visit[bex][bey] = 1;
76      // printf("%d %d\n",enx,eny);
77       if((limit - (ABS(enx -bex) + ABS(eny-bey))) % 2 != 1  )
78            dfs(bex,bey,0);
79       if(ok)
80           printf("YES\n");
81       else printf("NO\n");
82     }
83 
84   return 0 ; 
85 }
View Code

 

posted on 2013-11-22 19:04  dark_dream  阅读(193)  评论(0编辑  收藏  举报