骑士的移动

题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=83498#problem/E

题意:

      输入标准8*8国际象棋棋盘上的两个格子(列用a~h表示,行用1~8表示),求马最少需要多少步从起点跳到终点。(可输入多组案例)

     input:

     e2 e4

     a1 b2

     b2 c3

     f6 f6

     output:

     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 f6 to f6 takes 0 knight moves.

思路分析:

             求的是最短路,可以用BFS。

             要先把马会走的8个方向记为一个坐标变化的二维数组,a~h转化为1~8,设立一个二维数组记录马所到过的坐标。

             注意:马不能离开棋盘,马不能再次到达它所到过的地方。

             再利用BFS求最短路。

源代码如下:

 1 #include<iostream>

 2 #include<cstdio>

 3 #include<cstring>

 4 #include<queue>

 5 using namespace std;

 6 int s[8][2]={{2,-1},{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2}};     //八个方向

 7 int ch[10][10];

 8 struct node

 9 {

10     int x,y,count;

11 }a,b;

12 int main()

13 {

14     

15     char c1,c2;

16     int r1,r2,c3,c4;

17     while(cin>>c1>>r1>>c2>>r2)

18     {

19         c3=c1-'a'+1;                 

20         c4=c2-'a'+1;

21         memset(ch, 0, sizeof(ch));    //地图清零,以便记录马是否到过

22         ch[c3][r1]=1;

23         b.x=c3;b.y=r1;b.count=0;

24         queue<node> d;

25         d.push(b);

26         while(!d.empty())           //BFS

27         {

28             a=d.front();

29             d.pop();

30             if(a.x==c4&&a.y==r2)break;

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

32             {

33                 b.x=a.x+s[i][0];

34                 b.y=a.y+s[i][1];

35                 if(b.x<1||b.x>8||b.y<1||b.y>8)continue;

36                 if(ch[b.x][b.y]==1)continue;

37                 ch[b.x][b.y]=1;

38                 b.count=a.count+1;

39                 d.push(b);

40             }

41         }

42         printf("To get from %c%d to %c%d takes %d knight moves.\n",c1,r1,c2,r2,a.count);

43     }

44     return 0;

45 }

 

你可能感兴趣的:(移动)