Simple for the use of BFS, but still write too slow to write the TMD 1H, mainly not familiar with, after slowly familiar with, the model has been able to establish, the main problem is in the direction of the array of use above, must remember is starting from 0, and not starting from 1, resulting in errors.
#include <cstdio>#include<cstdlib>#include<iostream>using namespacestd;/*BFS*///Array of directionsintnextx[8][2]={ {-1,-2}, {-2,-1}, {1,2}, {2,1}, {1,-2}, {2,-1}, {-1,2}, {-2,1}};/*1 0 3 0 5 6 7 8 all 2 3 4 0 6 7 8 9 1 2 0 4 5 6 7 8 2 3 4 0 6 7 8 0 3 0 5 6 7 8 9 1 2 3 4 5*/structque{intX//the current A; intY//the current B; intStep//number of steps passed};intMain () {intI//Loop Variable intY1,y2; intx1,x2; intNowx,nowy; Charch[Ten]; intHead=1; intTail=1; structQue ques[ -]; while(Gets (ch)! =NULL) { //converts the number of inputs into corresponding numbersX1 = ch[0]-'a'+1; Y1= ch[1]-'0'; X2= ch[3]-'a'+1; Y2= ch[4]-'0'; //initialize the map to record the points traversed intmaps[Ten][Ten]={0}; Head=1; Tail=1; MAPS[X1][Y1]=1;//record the initial pointques[head].x =X1; Ques[head].y=Y1; Ques[head].step=0; Tail++; Nowx=X1; Nowy=Y1; if(nowx = = x2 && Nowy = =y2) { GotoF1; } while(head<tail) { for(i =0; I <8; i++) {nowx= ques[head].x + nextx[i][0]; Nowy= Ques[head].y + nextx[i][1]; if(nowx<=0|| Nowx>8|| nowy<=0|| Nowy>8) Continue; if(Maps[nowx][nowy] = =0) {Maps[nowx][nowy]=1; ques[tail].x=nowx; Ques[tail].y=Nowy; Ques[tail].step= Ques[head].step +1; Tail++; } if(nowx = = x2 && Nowy = =y2) { GotoF1; }} head++; } f1:printf ("To get from%c%d to%c%d takes%d Knight moves.\n", ch[0],y1,ch[3],y2,ques[tail-1].step); } return 0;}/*Sample Inpute2 e4a1 b2b2 c3a1 h8a1 h7h8 a1b1 c3f6 f6sample OutputTo get from E2 to E4 takes 2 Knight moves. To get from A1 to B2 takes 4 knight moves. To get from B2 to C3 takes 2 knight moves. To get from A1 to H8 takes 6 knight moves. To get from A1 to H7 takes 5 knight moves. To get from H8 to A1 takes 6 knight moves. To get from B1 to C3 takes 1 Knight moves. To get from F6 to F6 takes 0 knight moves.*/
Hdu1372,bfs Chess horse Walking Day