POJ 2243
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 5 int dir[8][2] = {-2,-1,-2,1,2,-1,2,1,1,-2,-1,-2,1,2,-1,2}; 6 7 struct node 8 { 9 int x; 10 int y; 11 int step; 12 node() 13 { 14 step = 0; 15 } 16 }; 17 18 queue<node> coll; 19 20 bool mark[8][8]; 21 22 node beg; 23 node end; 24 25 bool bfs(node p); 26 27 int main() 28 { 29 //freopen("acm.acm","r",stdin); 30 char s_1[2]; 31 char s_2[2]; 32 33 while(cin>>s_1>>s_2) 34 { 35 memset(mark,false,sizeof(mark)); 36 beg.x = s_1[0] - 'a'; 37 beg.y = s_1[1] - '0' - 1; 38 39 end.x = s_2[0] - 'a'; 40 end.y = s_2[1] - '0' - 1; 41 coll.push(beg); 42 mark[beg.x][beg.y] = true; 43 cout<<"To get from "<<s_1<<" to "<<s_2<<" takes "; 44 45 while(!coll.empty() && !bfs(coll.front())) 46 { 47 coll.pop(); 48 } 49 while(!coll.empty()) 50 { 51 coll.pop(); 52 } 53 cout<<" knight moves."<<endl; 54 } 55 } 56 57 bool bfs(node p) 58 { 59 int i; 60 int j; 61 if(p.x == end.x && p.y == end.y) 62 { 63 cout<<p.step; 64 return true; 65 } 66 int tem_i; 67 int tem_j; 68 node tem; 69 70 for(i = 0; i < 8; ++ i) 71 { 72 tem_i = p.x + dir[i][0]; 73 tem_j = p.y + dir[i][1]; 74 if(tem_i >= 0 && tem_i < 8 && tem_j >= 0 && tem_j < 8 && !mark[tem_i][tem_j]) 75 { 76 tem.x = tem_i; 77 tem.y = tem_j; 78 tem.step = p.step + 1; 79 mark[tem_i][tem_j] = true; 80 coll.push(tem); 81 } 82 } 83 return false; 84 }
关注我的公众号,当然,如果你对Java, Scala, Python等技术经验,以及编程日记,感兴趣的话。
技术网站地址: vmfor.com