UVa439——骑士的移动

简单bfs

 1 #include <iostream>
 2 #include <cstring>
 3 #include <string>
 4 #include <map>
 5 #include <set>
 6 #include <algorithm>
 7 #include <fstream>
 8 #include <cstdio>
 9 #include <cmath>
10 #include <stack>
11 #include <queue>
12 using namespace std;
13 const double Pi=3.14159265358979323846;
14 typedef long long ll;
15 const int MAXN=5000+5;
16 int dx[8]={-1,-1,-2,-2,1,1,2,2};
17 int dy[8]={-2,2,-1,1,-2,2,-1,1};
18 const int INF = 0x3f3f3f3f;
19 const int NINF = 0xc0c0c0c0;
20 const ll mod=1e9+7;
21 int M[9][9];
22 struct node{
23     int x;int y;int step;
24     node (int x=0,int y=0,int step=0)
25     {
26         this->x=x;
27         this->y=y;
28         this->step=step;
29     }    
30 }now,tim;
31 
32 int bfs(int x1,int y1,int x2,int y2,string str1,string str2)
33 {
34     
35     tim.x=x1;tim.y=y1;tim.step=0;
36     queue <node> Q;
37     Q.push(tim);
38     //cout <<x2<<" "<<y2<<endl; 
39     while(!Q.empty())
40     {
41         
42         tim=Q.front();Q.pop();
43         if(tim.x==x2&&tim.y==y2)
44         {
45             cout <<"To get from "<<str1<<" to "<<str2<<" takes "<<M[tim.x][tim.y]<<" knight moves.\n";
46             return 0;
47         }
48         for(int i=0;i<8;i++)
49         {
50             now.x=tim.x+dx[i];
51             now.y=tim.y+dy[i];
52             if(now.x>=1&&now.y<=8&&now.x<=8&&now.y>=1&&M[now.x][now.y]==-1)
53             {
54                 now.step=tim.step+1;
55                 M[now.x][now.y]=M[tim.x][tim.y]+1;
56                 Q.push(now);
57             }
58         }
59     }
60     return -1;
61 }
62 
63 int main()
64 {
65     string str1,str2;
66     while(cin>>str1)
67     {
68         cin>>str2;
69         int x1,x2,y1,y2;
70         memset(M,-1,sizeof(M));
71         x1=9-str1[1]+'0';
72         y1=str1[0]-'a'+1;
73         y2=str2[0]-'a'+1;
74         x2=9-str2[1]+'0';
75         M[x1][y1]=0;
76         //cout <<x1<<y1<<x2<<y2<<endl;
77         bfs(x1,y1,x2,y2,str1,str2);
78     }
79     return 0;
80 }

猜你喜欢

转载自www.cnblogs.com/Msmw/p/10731685.html