标签:
骑士巡游找最短路。
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 }
标签:
原文地址:http://www.cnblogs.com/huoxiayu/p/4439259.html