码迷,mamicode.com
首页 > 其他好文 > 详细

hdu 1372 AND poj 2243 bfs

时间:2015-04-19 17:35:44      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

骑士巡游找最短路。

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 using namespace std;
 5 
 6 const int N = 8;
 7 const int M = N * N;
 8 int step[N][N];
 9 int dir[N][2] = { 1, 2, 1, -2, -1, 2, -1, -2, 2, 1, 2, -1, -2, 1, -2, -1 };
10 
11 struct Node
12 {
13     int x, y;
14 
15     Node () {}
16 
17     Node ( int _x, int _y )
18     {
19         x = _x, y = _y;
20     }
21 
22 } q[M];
23 
24 bool ok( int x, int y )
25 {
26     return x >= 0 && x < N && y >= 0 && y < N && step[x][y] == -1;
27 }
28 
29 int bfs( char src[], char des[] )
30 {
31     int sx = src[0] - a, sy = src[1] - 1;
32     int ex = des[0] - a, ey = des[1] - 1;
33     memset( step, -1, sizeof(step) );
34     int head = 0, tail = 0;
35     q[tail++] = Node( sx, sy );
36     step[sx][sy] = 0;
37     while ( head < tail )
38     {
39         Node t = q[head++];
40         if ( t.x == ex && t.y == ey ) return step[t.x][t.y];
41         for ( int i = 0; i < N; i++ )
42         {
43             int xx = t.x + dir[i][0];
44             int yy = t.y + dir[i][1];
45             if ( ok( xx, yy ) )
46             {
47                 q[tail++] = Node( xx, yy );
48                 step[xx][yy] = step[t.x][t.y] + 1;
49             }
50         }
51     }
52     return -1;
53 }
54 
55 int main()
56 {
57     char s[3], t[3];
58     while ( scanf("%s%s", s, t) != EOF )
59     {
60         printf("To get from %s to %s takes %d knight moves.\n", s, t, bfs( s, t ));
61     }
62     return 0;
63 }

hdu 1372 AND poj 2243 bfs

标签:

原文地址:http://www.cnblogs.com/huoxiayu/p/4439259.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!