標籤:
騎士的移動
題目連結:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=83498#problem/E
題目:
Description
A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.
Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.
Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.
Input Specification
The input file will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.
Output Specification
For each test case, print one line saying "To get from xx to yy takes n knight moves.".
Sample Input
e2 e4a1 b2b2 c3a1 h8a1 h7h8 a1b1 c3f6 f6
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.
題意:
輸入標準8*8國際象棋棋盤上的兩個格子(列用a~h表示,行用1~8表示),
求馬最少需要多少步從起點跳到終點。
分析:
馬每次有八個方向可以走動,直接用BFS進行搜尋即可;
不過要注意當馬在棋盤的邊境時有的方向不能走(不能越境),
還有不能重複走(走過的地方進行標記)。
1 #include <iostream> 2 #include <stdio.h> 3 #include <string.h> 4 #include <queue> 5 using namespace std; 6 int c[9][9]; 7 int dir[8][2] = {{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2}}; 8 typedef struct 9 {10 int x,y,count;11 }node;12 node start,finish;13 int main()14 {15 char row,end;16 int col,ed;17 int min;18 while(scanf("%c",&row)!=EOF)19 {20 scanf("%d",&col);21 getchar();22 scanf("%c%d",&end,&ed);23 getchar();24 start.x = row-‘a‘+1;25 start.y = col;26 finish.x = end-‘a‘+1;27 finish.y = ed;28 if(start.x==finish.x&&start.y==finish.y)29 min = 0;30 else 31 {32 memset(c,0,sizeof(c));33 node pre,cur;34 start.count = 0;35 queue<node> q;36 q.push(start);37 c[start.x][start.y] = 1;38 while(!q.empty())39 {40 pre = q.front();41 q.pop();42 if(pre.x == finish.x&&pre.y == finish.y)43 min=pre.count;44 for(int i = 0; i < 8; i++)45 {46 cur.x = pre.x + dir[i][0];47 cur.y = pre.y + dir[i][1];48 if(cur.x<1||cur.x>8||cur.y<1||cur.y>8)continue;49 if(c[cur.x][cur.y]==1)continue;50 c[cur.x][cur.y] = 1;51 cur.count = pre.count + 1;52 q.push(cur);53 }54 }55 }56 printf("To get from %c%d to %c%d takes %d knight moves.\n",row,col,end,ed,min);57 }58 return 0;59 }
BFS 騎士的移動