hdu1372 the Traveling Knight Problem

一个搜索的题目,按照八个方向,不过输入的时候要将字母转换一下,在进行计算。

 #include<iostream>
 #include<cstring>
 #include<string>
 #include<queue>
 using namespace std;
 
 struct Node 
 {
     int x;
     int y;
     int step;
 };
 
 int dir[8][2]={-2,-1,-2,1,-1,-2,-1,2,1,-2,1,2,2,-1,2,1};
 
 int bfs(string st,string end)
 {
     bool visit[10][10];
     memset(visit,false,sizeof(visit));
     Node s,e,t;
     queue<Node> q;
     s.x=st[0]-'a';      
     s.y=st[1]-'0';
     s.step=0;
     e.x=end[0]-'a';
     e.y=end[1]-'0';
     if(s.x==e.x&&s.y==e.y)
         return 0;
     q.push(s);
     visit[s.x][s.y]=true;
     while(!q.empty())
     {
         s=q.front();
         q.pop();
         for(int i=0;i<8;++i)
         {
             t.x=s.x+dir[i][0];
             t.y=s.y+dir[i][1];
             t.step=s.step+1;
             if(visit[t.x][t.y]==false)
             {
                 if(t.x==e.x&&t.y==e.y)
                     return t.step;
                 if(t.x>=0&&t.x<8&&t.y>0&&t.y<=8)
                 {
                     visit[t.x][t.y]=true;
                     q.push(t);
                 }
             }
         }
     }
     
 }
 
 int main()
 {
     string st,end;
     while(cin>>st>>end)
     {
         cout<<"To get from "<<st<<" to "<<end<<" takes "<<bfs(st,end)<<" knight moves."<<endl;
     }
     return 0;
 }



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值