This question was once written, BFs. With a queue, not much to say, on the code:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <queue>using namespace std; int map[10][10];int visit[10][10];int dist[10][10];int dx[8]={-2,-2,-1,-1,1,1,2,2};int dy[8]={-1,1,-2,2,-2,2,-1,1}; Char a[5];int x2,y2;struct node{int x, y;}; queue<node>q; int BFS (node T) {if (t.x==x2&&t.y==y2) {return dist[t.x][t.y];} Else{while (!q.empty ()) {node M = Q.front (); Q.pop (); if (m.x==x2&&m.y==y2) return dist[m.x][m.y];for (int i=0; i <8; i++) {int xx = M.x+dx[i];int yy = m.y+dy[i];if (!visit[xx][yy]&&xx>0&&yy>0&&xx<=8 &&yy<=8) {node n; n.x = XX;N.Y = Yy;q.push (n);d ist[xx][yy] = dist[m.x][m.y]+1;visit[xx][yy] = 1;}}}} int main () {int x1,y1,i,j;while (gets (a)) {y1 = a[0]-' a ' +1;x1 = a[1]-' 0 '; y2 = a[3]-' a ' +1;x2 = a[4]-' 0 ';//printf ("%d%d%d%d\ n ", x1,y1,x2,y2); node T; T.x = x1; T.y = Y1;memset (dist,0,sizeof (Dist)), memset (visit,0,sizeof (visit)), Q.push (t), BFS (t);p rintf ("To get from%c%c to%c%c Takes%d Knight moves.\n ", a[0],a[1],a[3],a[4],dist[x2][y2]); while (!q.empty ()) {Q.pop ();}} return 0;}
UVA 439 Knight Moves Knight Move