It can be understood that the horse in chess goes the "Day" glyph, the shortest number of steps required from the first position to the second position, and a simple BFS
Each step must be judged whether it reaches the target point at a time.
Because BFS write not much, has been using Dfs thinking understanding, recursive write always overflow, timeout ~ ~
#include"Cstdio"#include"iostream"#include"CString"#include"Queue"using namespacestd;intdx[8]={-1,1,-2,2,-2,2,-1,1};intdy[8]={-2,-2,-1,-1,1,1,2,2};intvis[Ten][Ten];structpoint{intx; inty; intLevel ;};BOOLjudge (point P) {if(vis[p.x][p.y]| | P.x>8|| p.x<=0|| P.y>8|| p.y<=0)return false; return true;}intMain () {Chara1,b; intans; Point P1,p2; while(SCANF ("%c%d%c%d", &a1,&p1.y,&b,&p2.y)! =EOF) {GetChar (); memset (Vis,0,sizeof(VIS)); Ans=0; p1.x=a1-'a'+1;p 2.x=b-'a'+1; P1.level=0; Queue<point>Q; Q.push (p1); VIS[P1.X][P1.Y]=1; Point A; while(!Q.empty ()) {a=Q.front (); Q.pop (); if(A.X==P2.X&&A.Y==P2.Y) {ans=a.level; Break;} for(intI=0;i<8; i++) {Point temp; Temp.x=a.x+Dx[i]; TEMP.Y=a.y+Dy[i]; Temp.level=a.level+1; if(Judge (temp)) {VIS[TEMP.X][TEMP.Y]=1; Q.push (temp); }}} printf ("To get from%c%d to%c%d takes%d Knight moves.\n", A1,p1.y,b,p2.y,ans); } return 0;}View Code
POJ 2243:knight Moves (BFS)