Knight Moves

来源:互联网 发布:一个hdmi网络传输器 编辑:程序博客网 时间:2024/05/01 17:31
#include <stdio.h>#include <string.h>#include <math.h>#include <stdlib.h>#include <iostream> #include <queue>  using namespace std; int dx[8]={-2,-1,1,2, 2, 1,-1,-2};int dy[8]={ 1, 2,2,1,-1,-2,-2,-1};bool visit[50][50];struct node{   int x;   int y;   int num;}M[2];queue<node>Q;bool f(int x,int y){   if(x<1||x>'h'-'a'+1||y<1||y>8)       return false;    return true; }int bfs(node start,node end){   memset(visit,false,sizeof(visit));   while(!Q.empty())      Q.pop();   node head,temp;   Q.push(start);    start.num=0;   while(!Q.empty())   {      head=Q.front();      if(head.x==end.x&&head.y==end.y)        return head.num;      for(int i=0;i<8;i++)      {         temp.x=head.x+dx[i];         temp.y=head.y+dy[i];         if(!visit[temp.x][temp.y]&&f(temp.x,temp.y))         {                temp.num=head.num+1;                       Q.push(temp);         }                   }        Q.pop();                   }}int main(){      //freopen("in.txt","r",stdin);   // freopen("out.txt","w",stdout);    char a,b;    int ans;    while(scanf("%c%d %c%d\n",&a,&M[0].y,&b,&M[1].y)==4)    {       M[0].x=a-'a'+1;       M[1].x=b-'a'+1;       ans=bfs(M[0],M[1]);       printf("To get from %c%d to %c%d takes %d knight moves.\n",a,M[0].y,b,M[1].y,ans);                   }    return 0;}

原创粉丝点击