标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8831 Accepted Submission(s): 5202
Sample 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 a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.
1 #include <iostream> 2 #include <cstdio> 3 #include <queue> 4 #include <cstring> 5 using namespace std; 6 int dx[]={1,-1,1,-1,2,-2,2,-2}; 7 int dy[]={2,-2,-2,2,1,-1,-1,1}; 8 int vis[9][9]; 9 struct point 10 { 11 int x; 12 int y; 13 int t; 14 }st,tem,nex; 15 int sx,sy,ex,ey,tim; 16 char a,b,c,d; 17 void bfs() 18 { 19 queue<point> s; 20 st.x=sx,st.y=sy; 21 st.t=0; 22 s.push(st); 23 memset(vis,0,sizeof(vis)); 24 while(!s.empty()) 25 { 26 tem=s.front(); 27 s.pop(); 28 29 if(tem.x==ex&&tem.y==ey) 30 { 31 tim=tem.t; 32 return; 33 } 34 if(vis[tem.x][tem.y]||tem.x<=0||tem.y<=0||tem.x>8||tem.y>8) 35 continue; 36 vis[tem.x][tem.y]=1; 37 for(int i=0;i<8;i++) 38 { 39 int nx=tem.x+dx[i]; 40 int ny=tem.y+dy[i]; 41 int nt=tem.t+1; 42 nex.x=nx,nex.y=ny,nex.t=nt; 43 s.push(nex); 44 } 45 } 46 } 47 int main() 48 { 49 freopen("in.txt","r",stdin); 50 while(scanf("%c%c %c%c",&a,&b,&c,&d)!=EOF) 51 { 52 getchar(); 53 tim=0; 54 sy=a-‘a‘+1,sx=b-‘0‘; 55 ey=c-‘a‘+1,ex=d-‘0‘; 56 bfs(); 57 printf("To get from %c%c to %c%c takes %d knight moves.\n",a,b,c,d,tim); 58 } 59 }
标签:
原文地址:http://www.cnblogs.com/a1225234/p/5036504.html