sicily 1936.knight moves


问题描述

  国际象棋的马的移动问题,给出初始结束两个点,求出从初始到结束的最小步数。

方法

  还是用的bfs方法,因为正好bfs中搜索的层数就是马的步数,求最小步数非常合适。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include<string>
#include<queue>
#include<cstdio>
#include<cstring>
using namespace std;
const int BOARD_SIZE = 8;
int (int last, int way){
int lastx = last / BOARD_SIZE;
int lasty = last % BOARD_SIZE;
int x, y;
switch (way){
case 0:
x = lastx - 1;
y = lasty + 2;
break;
case 1:
x = lastx + 1;
y = lasty + 2;
break;
case 2:
x = lastx + 2;
y = lasty + 1;
break;
case 3:
x = lastx + 2;
y = lasty - 1;
break;
case 4:
x = lastx + 1;
y = lasty - 2;
break;
case 5:
x = lastx - 1;
y = lasty - 2;
break;
case 6:
x = lastx - 2;
y = lasty - 1;
break;
case 7:
x = lastx - 2;
y = lasty + 1;
break;
}
if (x < 0 || y < 0 || x >= BOARD_SIZE || y >= BOARD_SIZE){
return -1;
}
return x * BOARD_SIZE + y;
}
struct Board{
bool board[64];
int last;
Board(int last) :last(last){
for (int i = 0; i < 64; i++){
board[i] = false;
}
board[last] = true;
}
Board(const Board& board){
this->last = board.last;
memcpy(this->board, board.board, 64);
}
void next(int move){
last = move;
board[move] = true;
}
};
int find(int start, int end){
if (start == end)
return 0;
queue<Board*> q1, q2;
queue<Board*>* curQ = &q1;
queue<Board*>* nextQ = &q2;
q1.push(new Board(start));
int layer = 0;
while (!curQ->empty() || !nextQ->empty()){
layer++;
while (!curQ->empty()){
Board* cur = curQ->front();
curQ->pop();
for (int i = 0; i < 8; i++){
int next = move(cur->last, i);
if (next == end){
return layer;
}
if (next != -1 && !cur->board[next]){
Board* n = new Board(*cur);
n->next(next);
nextQ->push(n);
}
}
}
queue<Board*>* tmp = curQ;
curQ = nextQ;
nextQ = tmp;
}
return -1;
}
int tran(char m[3]){
return (m[0] - 'a') * BOARD_SIZE + (m[1] - '0') - 1;
}
int main(){
int a;
cin >> a;
while (a--){
char start[3];
char end[3];
cin >> start >> end;
start[2] = '