Knight Moves
Time Limit: 1000MS |
|
Memory Limit: 65536K |
Total Submissions: 11223 |
|
Accepted: 6331 |
Description A Friend of you doing in the traveling Knight problem (TKP) where you were to find the shortest Closed tour of Knight moves this visits each square of a given set of n squares on a chessboard exactly once. He thinks the most difficult part of the problem is determining the smallest number of knight moves between the given Squares and that, once you has accomplished this, finding the tour would is easy.
Of course you know the It is vice versa. Him to write a program that solves the "difficult" part.
Your Job is to write a program, takes, squares A and B as input and then determines the number of knight M Oves on a shortest the route from a to B.
Input the input would contain one or more test cases. Each test case consists the one line containing the squares separated by one space. A square is a string consisting of a letter (A-h) representing the column and a digit (1-8) representing the row on the CH Essboard.
Output for each test case, print one line saying "to get from XX to YY takes N Knight moves."
Sample Input
E2 e4
A1 B2
b2 c3
A1 h8
A1 H7
h8 A1
B1 C3
f6 f6
Sample Output
To 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.
Do not open the array too large. Also remember to empty the queue.
#include <cstdio> #include <iostream> #include <cstring> #include <queue> #include <
Algorithm> #include <vector> using namespace std;
const int N = 200;
int n, m;
Char Color[n][n];
int vist[n][n];
int dx[8] = {-2,-2,-1,-1, 1, 1, 2, 2};
int dy[8] = {-1, 1,-2, 2,-2, 2,-1, 1};
int xx;
int yy;
int ans;
struct node {int x;
int y;
char c;
int num;
};
queue<node>q;
Node A, B;
void BFs () {vist[a.x][a.y]=1;
while (!q.empty ()) {Node temp = Q.front (); if (temp.x==b.x && temp.y==b.y) {printf ("to get from%c%d to%c%d takes%d Knight moves.\n",
A.C, A.y, B.C, B.y, temp.num);
return;
} q.pop ();
for (int i=0; i<8; i++) {xx = temp.x + dx[i];
yy = Temp.y + dy[i];
if (xx<1 | | xx>8 | | yy<1 | | yy>8 | | vist[xx][yy]) continue;
Node Next;
Next.x = XX; Next.y = yy;
next.num=temp.num+1;
Vist[xx][yy]=1;
Q.push (next);
}}} int main () {int i,j;
while (~scanf ("%c%d%c%d", &A.C, &a.y, &B.C, &b.y)) {GetChar ();
while (!q.empty ()) Q.pop ();
memset (vist, 0, sizeof (vist));
a.x = A.C-' a ' +1;
b.x = B.C-' a ' +1;
node first;
First.x = a.x;
First.y = A.Y;
first.num=0;
Ans = 0;
Q.push (first);
BFS ();
} return 0;
}