Knight Moves

来源:互联网 发布:java final存放区域 编辑:程序博客网 时间:2024/05/01 10:10

这个是我们今天训练的题目,花了我大半天,一开始用深搜提交超时,后来改为广搜,提交错误,呵呵,后来看了网友的解题报告,总算看懂了,并且提交正确,这个是网友的代码,有些地方加了注释,如果有错误的地方请各位提出来,我们一起交流学习》。。。

描述

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.

输入

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.

输出

For each test case, print one line saying "To get from xx to yy takes n knight moves.".

样例输入

e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6

样例输出

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.
#include <iostream>#include <stdlib.h>#include <stdio.h>#include <string.h>#include <queue>using namespace std;struct Node   //创建一个结构体{    int x;    int y;    int step;};int sx,sy,ex,ey;//定义开始点和结束点int map[10][10];int dir[8][2]={-2,1,-2,-1,-1,2,-1,-2,1,2,1,-2,2,-1,2,1};//表示八个方向Node first,next;int BFS(){    int i;    queue<Node>Q;   //创建一个队列,Q    first.x=sx;    first.y=sy;    first.step=0;    Q.push(first);   //把first加入队列    map[first.x][first.y]=1;    while(!Q.empty())//判断队列是否为空    {        first=Q.front();      //返回第一个元素        Q.pop();         //返回第一个元素        if(first.x==ex&&first.y==ey) return first.step;//如果找到位子,则结束循环返回最短部数        for(i=0;i<8;i++)   //此循环是模拟马走的八个方向        {            next.x=first.x+dir[i][0];            next.y=first.y+dir[i][1];            if(next.x<0||next.x>=8||next.y<0||next.y>=8) continue;            if(map[next.x][next.y]==1)  continue;            map[next.x][next.y]=1;//用map数组标记,以免下次重复走            next.step=first.step+1;            Q.push(next);  //在末尾加入一个元素        }    }}int main(){    char a[3],b[3];    int i,j;    while(scanf("%s%s",&a,&b)!=EOF)    {        sy=a[0]-'a';        sx=a[1]-'1';        ey=b[0]-'a';        ex=b[1]-'1';        memset(map,0,sizeof(map));//把map数组初始化为0        printf("To get from %s to %s takes %d knight moves.\n",a,b,BFS());    }    return 0;}


原创粉丝点击