Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2136 Accepted Submission(s): 1354
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6
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.queue<int> Q; //这个就是建立一个队列,名字叫Q,队列里的所有元素都是int整型;
2.Q.push(a); //这个就是将一个元素a,push进去排队;
3.b=Q.front(); //这个就是队列Q的排最前第一个的元素的值赋给b;
4.Q.pop(); //这个就是将排第一的元素移出队列,第二个的自然跟上;
5.Q.empty(); //这个就是判断队列Q是否为空,如果空就是1,不空就是0。
这几天一直都在做广搜bfs,首先要说一下这题,个人觉得最经典的题目就是这题---骑士游历。这题给我的启发很大,对付这类的问题有信心了。
代码:
#include <iostream> #include <stdio.h> #include <memory.h> #include <queue> using namespace std; int xx[8] = {1, 2, 1, 2, -1, -2, -1, -2}; int yy[8] = {2, 1, -2, -1, 2, 1, -2, -1}; char c1, c2; int b1, b2, x1, x2, y1, y2; bool ch[10][10]; struct point { int x, y, step; }n, m; int main() { int i; while(cin>>c1>>b1>>c2>>b2) { x1 = c1 - 'a' + 1; x2 = c2 - 'a' + 1; y1 = b1; y2 = b2; memset(ch, false, sizeof(ch)); n.x = x1; n.y = y1; n.step = 0; ch[n.x][n.y] = true; queue<point> P; P.push(n); while(!P.empty()) { m = P.front(); P.pop(); if(m.x == x2 && m.y == y2) break; for(i = 0; i < 8; i++) { n.x = m.x + xx[i]; n.y = m.y + yy[i]; n.step = m.step + 1; if(n.x>0 && n.x<=8 && n.y>0 && n.y<=8 && !ch[n.x][n.y]) { ch[n.x][n.y] = true; P.push(n); } } } printf("To get from %c%d to %c%d takes %d knight moves.\n", c1, y1, c2, y2, m.step); } return 0; }