1 # include <iostream> 2 # include <cstring> 3 # include <queue> 4 using namespace STD; 5 6 int isvis [9] [9]; // record whether the location is accessed 7 int Stax, stay, endx, Endy; 8 char start [3], end [3]; // start and end position 9 typedef struct node10 {11 int X, Y, movenum; 12} knight; 13 int move [8] [2] = {-1,-2, 1, 2, 1, 1,-2, 1, 2,-1,-1,-2,-2,-1}; // The Moving position of the server guard 14 void BFS (int x, int y); 15 16 int main () {17 // freopen ("D: \ t.txt", "r", stdin); 18 while (CIN> Start> end) {19 Stax = start [0]-'A' + 1; 20 stay = start [1]-'0 '; 21 endx = end [0]-'A' + 1; 22 Endy = end [1]-'0 '; // process the position of the input piece 23 BFS (Stax, stay); 24} 25 return 0; 26} 27 void BFS (int x, int y) {28 knight M, N; 29 queue <knight> que; 30 31 m. X = x; 32 m. y = y; 33 m. movenum = 0; 34 memset (isvis, 0, sizeof (isvis); // initialize 35 isvis [M. x] [M. y] = 1; 36 que. push (m); 37 while (! Que. empty () {38 m = que. front (); 39 que. pop (); 40 if (M. X = endx & M. y = Endy) {41 cout <"to get from" <start [0] <start [1] <"to" <End <"takes" <m. movenum <"knight moves. "<Endl; 42 break; 43} // if the end point is reached, end 44 for (INT I = 0; I <8; I ++) {45 if (M. X + move [I] [0]> 0) & (M. X + move [I] [0] <9) & (M. Y + move [I] [1]> 0) & (M. Y + move [I] [1] <9) 46 &&! Isvis [M. X + move [I] [0] [M. Y + move [I] [1]) {// determines whether the movement is out of range and whether it is accessed 47 n. X = m. X + move [I] [0]; 48 N. y = m. Y + move [I] [1]; 49 n. movenum = m. movenum + 1; 50 que. push (n); 51} 52} 53} 54 55}
Belongs to BFs.
UV 439 knight moves