HDU 1372 Knight Moves 广搜

http://acm.hdu.edu.cn/showproblem.php?pid=1372

题意:

  一个8*8的正方形棋盘,行用a-h标记,列用1-8标记。

   给定两个坐标,要求你从一个坐标到另一个坐标的最小步数。

  移动和象棋中的马一样,走 “日”  字。

 

坑爹:

  英文太难了,半天不知道走 “日” 字 ,真是我日啊。

 

解法:

  广搜八个方向。

 

View Code
 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 
 5 int map[8][2]={{2,1},{2,-1},{1,-2},{1,2},{-1,-2},{-1,2},{-2,1},{-2,-1}}; 
 6 int used[10][10];
 7 char c;
 8 int starti;
 9 int startj;
10 char d;
11 int overi;
12 int overj;
13 
14 struct node
15 {
16     int x;
17     int y;
18     int rank;
19 };
20 
21 void BFS()
22 {
23     queue<struct node> Q;
24     struct node a;
25     a.x = starti;
26     a.y = startj;
27     a.rank = 0;
28     used[a.x][a.y] = 1;
29     Q.push(a);
30     
31     while(!Q.empty())
32     {
33         a = Q.front();
34         Q.pop();
35 
36         int i;
37         for(i = 0; i<8; i++)
38         {
39             node b;
40             b.x = a.x + map[i][0];
41             b.y = a.y + map[i][1];
42             if(b.x>0 && b.x <=8 && b.y >0 && b.y<=8 && !used[b.x][b.y])
43             {
44                 b.rank = a.rank + 1;
45                 used[b.x][b.y] = 1;
46                 Q.push(b);    
47                 if(b.x == overi && b.y == overj)
48                 {
49                     cout<<"To get from "<<c<<starti<<" to "<<d<<overi<<" takes "<<b.rank<<" knight moves."<<endl;
50                     return;
51                 }
52             }
53         }
54     }
55 }
56 
57 
58 int main()
59 {
60     while(scanf("%c%d %c%d",&c,&starti,&d,&overi)!=EOF)
61     {
62         memset(used,0,sizeof(used));
63         startj = c - 'a' + 1;
64         overj = d - 'a' + 1;
65         if(starti == overi && startj == overj)
66         {
67             cout<<"To get from "<<c<<starti<<" to "<<d<<overi<<" takes "<<0<<" knight moves."<<endl;
68             continue ;
69         }
70         BFS();    
71     }
72     return 0;
73 }

 

posted @ 2012-09-03 19:47  pc....  阅读(173)  评论(0编辑  收藏  举报