Title: Https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=839&page=show_ problem&problem=380
Idea: Use BFS to find the shortest distance to the end.
Tip: Use a dir array and two for loops to enumerate the eight nodes connected to one node.
/*Knight Moves (UVa 439)*/#include<iostream>#include<cstring>#include<queue>using namespacestd;Const intMAXN =Ten;structpoint{intR, c, CNT; Point (intRintCintcnt): R (R), C (c), CNT (CNT) {}};intVIS[MAXN][MAXN]; intDir[] = {1,-1,2,-2};intR1, C1, R2, C2;//coordinates of the start and end pointsintBFS (intX1,intY1,intX2,inty2);intMain () {//freopen ("Input.txt", "R", stdin); Chars1[2], s2[2]; while(Cin >> S1 >>S2) {R1= s1[1] -'0'; C1= s1[0] -'a'+1; R2= s2[1] -'0'; C2= s2[0] -'a'+1; cout<<"To get from"<< S1 <<" to"<< S2 <<"takes"<< BFS (R1, C1, R2, C2) <<"Knight moves."<<Endl; } return 0;}intBFS (intX1,intY1,intX2,inty2) {memset (Vis,0,sizeof(VIS)); Queue<Point>Q; Q.push (Point (x1, y1,0)); VIS[X1][Y1]=1; while(!Q.empty ()) {Point U=Q.front (); Q.pop (); if(U.R = = R2 && u.c = =C2)returnu.cnt; for(intI=0; i<4; i++) {//join a walk-in node to a queue for(intj=0; j<4; J + +){ if(I! = J &&-dir[i]! =Dir[j]) {Point V (U.R+dir[i], u.c+dir[j], u.cnt+1); if(v.r>=1&& v.r<=8&& v.c>=1&& v.c<=8&& vis[v.r][v.c]==0) {Q.push (v); VIS[V.R][V.C]=1; } } } } }}
Knight Moves (UVa 439) BFS