UVa439——骑士的移动
Posted msmw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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. "; 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 }
以上是关于UVa439——骑士的移动的主要内容,如果未能解决你的问题,请参考以下文章
习题6-4 骑士的移动(Knight Moves,UVa 439)