zju1091

#include<iostream>

using namespace std;

#include<queue>

 

#define size 10

int board[size][size];//棋盘

 

class point

{

public:

       int x;

       int y;

};

point start,end;

queue<point> q;//辅助队列

 

int cur_level,next_level,level;

int dir[8][2]={ {-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1} };

 

 

int bfs()

{

       point temp=start,temp2;

       while( !q.empty() )

              q.pop();

       q.push(temp);

       cur_level=1;//当前处理的那层有多少个节点

       next_level=0;//下一层有多少个节点

       level=0;//当前处理的是第几层

       for(int i1=1;i1<=8;i1++)

              for(int i2=1;i2<=8;i2++)

                     board[i1][i2]=0;

       board[start.x][start.y]=1;

       while(1)

       {

              while(cur_level>0)

              {

                     cur_level--;

                     temp=q.front();

                    

                     for(int i=0;i<8;i++)

                     {

                            temp2.x=temp.x+dir[i][0];

                            temp2.y=temp.y+dir[i][1];

                            if(temp2.x == end.x && temp2.y==end.y)

                            {

                                   return level+1;

                            }

                            else

                            {

                                   if( temp2.x>=1 && temp2.x<=8 && temp2.y>=1 && temp2.y<=8 && board[temp2.x][temp2.y]==0 )

                                   {

                                          q.push(temp2);

                        board[temp2.x][temp2.y]=1;

                                          next_level++;

                                   }

                            }

                     }

                     q.pop();

              }

              cur_level=next_level;

              next_level=0;

              level++;

       }

}

 

 

 

 

int main()

{

       char ch1,ch2,ch3,ch4;

 

       while(cin>>ch1>>ch2>>ch3>>ch4)

       {

              start.y=ch1-'a'+1;

              start.x=ch2-'0';

              end.y=ch3-'a'+1;

              end.x=ch4-'0';

              cout<<"To get from "<<ch1<<ch2<<" to "<<ch3<<ch4<<" takes ";

              if(start.x==end.x && start.y==end.y)

              { cout<<0;}

              else cout<<bfs();

              cout<<" knight moves."<<endl;

       }

       return 0;

}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值