hdu1372Knight Moves

来源:互联网 发布:linux nat共享上网 编辑:程序博客网 时间:2024/06/06 01:37

很简单的一道广搜题,最近广搜还是做了有几道咯。这是上个专题回家落下的一道题,今天A了一下,还是蛮简单的。对深搜还是不太懂。这道题的代码可以当做很好的广搜模板。(七夕,晚上跑来基地一群光棍在喊寂寞。哈哈,很搞笑哦)

<code>

#include<iostream>
#include<queue>
using namespace std;
#define size 10
int flag[size][size];
char str1[5],str2[5];
int a,b,c,d;
int dir[8][2]={{-2,-1},{-2,1},{2,-1},{2,1},{-1,-2},{-1,2},{1,-2},{1,2}};
struct Node
{
     int x,y;
     int step;
}cur,next;
void bfs()
{   
     int i,tx,ty;
     queue<Node>que;
     cur.x=a;
     cur.y=b;
     cur.step=0;
     flag[cur.x][cur.y]=1;
     que.push(cur);
     while(!que.empty())
     {
         cur=que.front();
         que.pop();
         if(cur.x==c&&cur.y==d)
         {
           printf("To get from %s to %s takes %d knight moves./n",str1,str2,cur.step);
           return;
         }
         for(i=0;i<8;i++)
         {
           tx=cur.x+dir[i][0];
           ty=cur.y+dir[i][1];
           if(tx>=0&&tx<8&&ty>=0&&ty<8&&flag[tx][ty]==0)
           {
              next.x=tx;
              next.y=ty;
              next.step=cur.step+1;
              que.push(next);
              flag[tx][ty]==1;
           }
         }
     }
}
int main()
{
    while(cin>>str1>>str2)
    {
         a=str1[0]-'a';
         b=str1[1]-'1';
         c=str2[0]-'a';
         d=str2[1]-'1';
         memset(flag,0,sizeof(flag));
         bfs();
    }
    return 0;
}
/*

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.
*/

原创粉丝点击