Knight Moves
Description
A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Input
The input will contain one or more test cases. Each test case consists of one line containing two 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 chessboard.
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.
简单的bfs问题,还是码力不够,忘记了判断起始和终止位置相同的情况的判断,也忘记了访问过的节点进行标记这个操作,map[temp_y][temp_x] = 0;
结果出现了无效内存的应用。
#include<stdio.h>
#include<string.h>
typedef struct Q{
int x,y;
}QUEUE;
QUEUE result[100];
int head,tail,steps,add_step_flag;
int is_law(int x,int y){
return (x < 8&& x> -1 && y < 8 && y > -1)?1:0;
}
void bfs(int map[][18],int x,int y){
int i;
int temp_y;
int temp_x;
int dir[][2] = {1,2,
2,1,
2,-1,
1,-2,
-1,2,
-2,1,
-2,-1,
-1,-2
};
for(i = 0; i < 8; ++i){
temp_x = x + dir[i][0];
temp_y = y + dir[i][1];
if(is_law(temp_x,temp_y)){
if(map[temp_y][temp_x] == 1){
map[temp_y][temp_x] = 0;
result[tail].x = temp_x;
result[tail].y = temp_y;
++ tail;
}else if(map[temp_y][temp_x] == 0){
continue;
}else{
return ;
}
}
}
++head;
if(head == add_step_flag){
++steps;
add_step_flag = tail;
}
bfs(map,result[head].x,result[head].y);
}
int main(){
char begins[3];
char ends[3];
int map[18][18];
//FILE *fp;
//fp = freopen("in.txt","r",stdin);
while(~scanf("%s%s",begins,ends)){
steps = 1;
head = -1;
tail = 0;
add_step_flag = 0;
for(int i = 0; i < 8; ++i){
for(int j = 0;j < 8; ++j){
map[i][j] = 1;
}
}
map[begins[0]-'a'][begins[1] - '1'] = 0;
map[ends[0]-'a'][ends[1] - '1'] = 2;
if(strcmp(begins,ends)){
bfs(map,begins[1] - '1',begins[0]-'a');
}else{
steps = 0;
}
printf("To get from %s to %s takes %d knight moves.\n",begins,ends,steps);
}
return 0;
}