UVa-439 Knight Moves

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 struct Node
 4 {
 5     int r,c;
 6     Node(int a,int b) : r(a),c(b) {}
 7     Node() {}
 8 };
 9 const int dr[] = {-2,-2,-1,-1,1,1,2,2};
10 const int dc[] = {-1,1,-2,2,-2,2,-1,1};
11 
12 int r1,c1,r2,c2;
13 string in1,in2;
14 void read()
15 {
16     r1 = 8-(in1[1]-'0');c1 = in1[0]-'a';
17     cin >> in2;r2 = 8-(in2[1]-'0');c2 = in2[0]-'a';
18 }
19 
20 int d[9][9];
21 bool limit(Node u)
22 {
23     return u.r>=0&&u.r<=7&&u.c>=0&&u.c<=7;
24 }
25 int solve()
26 {
27     memset(d,-1,sizeof(d));
28     queue<Node> q;
29     q.push(Node(r1,c1));
30     d[r1][c1] = 0;
31     while(!q.empty())
32     {
33         Node u = q.front();
34         q.pop();
35         if(u.r==r2&&u.c==c2)    return d[r2][c2];
36         for(int i = 0; i < 8; i ++)
37         {
38             Node v = u;
39             v.r += dr[i];
40             v.c += dc[i];
41             if(limit(v)&&d[v.r][v.c]<0)
42             {
43                 d[v.r][v.c] = d[u.r][u.c] + 1;
44                 q.push(v);
45             }
46         }
47     }
48 }
49 
50 void print(int rnt)
51 {
52     cout << "To get from " <<in1<< " to " <<in2<< " takes " <<rnt<< " knight moves." << endl;
53 }
54 int main()
55 {
56     while(cin >> in1)
57     {
58         read();
59         int rnt = solve();
60         print(rnt);
61     }
62     return 0;
63 }

 

posted @ 2018-11-26 21:43  Asurudo  阅读(225)  评论(0编辑  收藏  举报