hdu 1372 Knight Moves bfs搜索

给定棋盘上的两个点,求马从起点走到终点所需的最小步数,马的走法如下(和象棋差不多),本题也是简单的BFS搜索。
hdu 1372 Knight Moves bfs搜索 - 某年某月 - zxj015的博客
 
 
#include <stdio.h>
#include <iostream>
#include <queue>
using namespace std;
int xf,yf,xt,yt,ans;
int dir[8][2]={{-2,1},{2,1},{-2,-1},{2,-1},{-1,2},{1,2},{-1,-2},{1,-2}};
bool visited[9][9];
struct node
{
       int x,y;
       int time;
};
void bfs()
{
     int i,a1,b1,front=-1,rear=-1,xx,yy;
     node in,out;
     queue<node>que;
     in.x=xf;
     in.y=yf;
     in.time=0;
     que.push(in);
     visited[xf][yf]=true;
     while(!que.empty())
     {
       out=que.front();
       que.pop();
       if(out.x==xt&&out.y==yt)
       {
         ans=out.time;
         return;
       }
       for(i=0;i<8;i++)
       {
         xx=out.x+dir[i][0];
         yy=out.y+dir[i][1];
         if(xx<0||yy<0||xx>7||yy>7||visited[xx][yy])
          continue;
         in.x=xx;
         in.y=yy;
         in.time=out.time+1;
         visited[xx][yy]=true;
         que.push(in);
       }
     }
}
       
main()
{
      int i,j,flag,a,b;
      char c1,ci,c2;
      while(scanf("%c%d%c%c%d",&c1,&xf,&ci,&c2,&xt)!=EOF)
      {
         getchar();
         memset(visited,false,sizeof(visited));
         yf=c1-97;
         yt=c2-97;
         xf--;xt--;
         bfs();
         printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,++xf,c2,++xt,ans);
      }
}
posted @ 2011-03-22 20:26  CoderZhuang  阅读(116)  评论(0编辑  收藏  举报