1030 Knight Moves:BFS

宽度优先搜索(BFS)

上一次吧DFS错当成BFS写了一篇解题报告,哎呀囧啊。幸好没人发现。

言归正传,先上一道例题

Knight Moves

时间限制: 1秒  内存限制: 64M

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

The input 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

For each test case, print one line saying "To get from xx to yy takes n knight moves.".

 

Sample Input

e2 e4

a1 b2

b2 c3

a1 h8

a1 h7

h8 a1

b1 c3

f6 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.


题目是够啰嗦的

当然,宽搜不是我能想出来的,自然要有张伟大人的提醒,虽然这道题是非常基本的宽搜。但对于我来讲,能写出来就行,也就不管是谁提醒的了。

宽搜(BFS):


从起始点开始,对于当前节点所有能够发现的点存入队列,然后对队列中的每一个点进行处理,得出下一层的全部可发现节点,然后存入队列,直到找到终点。
主要内容看图。文字性的东西不好懂。
灰色的点是当前可以发现的点
黑色的点是当前所处理的点
白色的点是当前未遇到的点

特点:适用于寻找最短路径。
优点:机理比较好想
缺点:比较耗时,链表的搭建也比较有考验性(写得我都要暴走了)

代码:

  1. #include<stdio.h>  
  2. #include<string.h>  
  3. #include<stdlib.h>  
  4. typedef struct  
  5. {  
  6.     int x;  
  7.     int y;  
  8. } POINT;  
  9. POINT start,end;  
  10. struct node  
  11. {  
  12.     POINT p;  
  13.     struct node * next;  
  14. };  
  15. typedef struct node NODE;  
  16. NODE *p,*pn;  
  17. char field[10][10];  
  18. POINT getpoint(char buf[])  
  19. {  
  20.     POINT p;  
  21.     switch ( buf[0] )  
  22.     {  
  23.     case 'a':p.x = 1;break;  
  24.     case 'b':p.x = 2;break;  
  25.     case 'c':p.x = 3;break;  
  26.     case 'd':p.x = 4;break;  
  27.     case 'e':p.x = 5;break;  
  28.     case 'f':p.x = 6;break;  
  29.     case 'g':p.x = 7;break;  
  30.     case 'h':p.x = 8;break;  
  31.     }  
  32.     switch ( buf[1] )  
  33.     {  
  34.     case '1':p.y = 1;break;  
  35.     case '2':p.y = 2;break;  
  36.     case '3':p.y = 3;break;  
  37.     case '4':p.y = 4;break;  
  38.     case '5':p.y = 5;break;  
  39.     case '6':p.y = 6;break;  
  40.     case '7':p.y = 7;break;  
  41.     case '8':p.y = 8;break;  
  42.     }  
  43.     return p;  
  44. }  
  45. int check(int a,int b)  
  46. {  
  47.     NODE * pp = NULL;  
  48.     if (  (0<a && a<=8)   
  49.         &&(0<b && b<=8)  
  50.         &&field[a][b] == 0  
  51.         )  
  52.     {  
  53.         pp = (NODE*)malloc(sizeof(NODE));  
  54.         pp->next = NULL;  
  55.         pp->p.x = a; pp->p.y = b;  
  56.         pn->next = pp;  
  57.         pn = pn->next;  
  58.         return 1;  
  59.     }  
  60.     else return 0;  
  61. }  
  62. int main()  
  63. {  
  64.     char s1[5],s2[5];  
  65.     while ( scanf("%s%s",s1,s2) != -1 )  
  66.     {  
  67.         memset(field,0,sizeof(field));  
  68.         start = getpoint(s1); end = getpoint(s2);  
  69.         p = (NODE*)malloc(sizeof(NODE)); pn = p;  
  70.         p->p = start;p->next = NULL;  
  71.         while( p != NULL )  
  72.         {  
  73.             if ( p->p.x == end.x && p->p.y == end.y )   
  74.                 printf("To get from %s to %s takes %d knight moves.\n",s1,s2,field[p->p.x][p->p.y]);  
  75.             else {  
  76.                 if ( check(p->p.x+2,p->p.y+1) ) field[p->p.x+2][p->p.y+1] = field[p->p.x][p->p.y] + 1;   
  77.                 if ( check(p->p.x+2,p->p.y-1) ) field[p->p.x+2][p->p.y-1] = field[p->p.x][p->p.y] + 1;   
  78.                 if ( check(p->p.x+1,p->p.y+2) ) field[p->p.x+1][p->p.y+2] = field[p->p.x][p->p.y] + 1;   
  79.                 if ( check(p->p.x+1,p->p.y-2) ) field[p->p.x+1][p->p.y-2] = field[p->p.x][p->p.y] + 1;   
  80.                 if ( check(p->p.x-1,p->p.y+2) ) field[p->p.x-1][p->p.y+2] = field[p->p.x][p->p.y] + 1;   
  81.                 if ( check(p->p.x-1,p->p.y-2) ) field[p->p.x-1][p->p.y-2] = field[p->p.x][p->p.y] + 1;   
  82.                 if ( check(p->p.x-2,p->p.y+1) ) field[p->p.x-2][p->p.y+1] = field[p->p.x][p->p.y] + 1;   
  83.                 if ( check(p->p.x-2,p->p.y-1) ) field[p->p.x-2][p->p.y-1] = field[p->p.x][p->p.y] + 1;   
  84.             }  
  85.             NODE *F=p;p = p->next;free(F);  
  86.         }  
  87.     }  
  88.     return 0;  
  89. }  



Sure, I can write a program that solves the "difficult" part of the TKP. Here's an implementation in Python: ```python # Define a function to convert a square string to a tuple of coordinates def square_to_coords(square): col = ord(square[0]) - ord('a') row = int(square[1]) - 1 return (col, row) # Define a function to convert a tuple of coordinates to a square string def coords_to_square(coords): col = chr(coords[0] + ord('a')) row = str(coords[1] + 1) return col + row # Define a function to find the shortest path between two squares using BFS def shortest_path(start, end): # Convert start and end squares to coordinates start_coords = square_to_coords(start) end_coords = square_to_coords(end) # Define the possible knight moves moves = [(-2,-1), (-1,-2), (1,-2), (2,-1), (2,1), (1,2), (-1,2), (-2,1)] # Initialize the queue with the starting position and a distance of 0 queue = [(start_coords, 0)] # Initialize a set to keep track of visited positions visited = set([start_coords]) # Loop until the queue is empty while queue: # Dequeue the next position and distance position, distance = queue.pop(0) # Check if we have reached the end position if position == end_coords: return distance # Generate all possible moves from the current position for move in moves: new_pos = (position[0] + move[0], position[1] + move[1]) # Check if the new position is within the bounds of the chessboard if new_pos[0] < 0 or new_pos[0] > 7 or new_pos[1] < 0 or new_pos[1] > 7: continue # Check if the new position has already been visited if new_pos in visited: continue # Add the new position to the queue and mark it as visited queue.append((new_pos, distance + 1)) visited.add(new_pos) # If we reach this point, there is no path from start to end return -1 # Read input from file with open('input.txt', 'r') as f: for line in f: # Parse the input start, end = line.strip().split() # Find the shortest path and print the result distance = shortest_path(start, end) print("To get from {} to {} takes {} knight moves.".format(start, end, distance)) ``` This program reads input from a file called 'input.txt' and prints the shortest path between each pair of squares using the BFS algorithm. Each line of the input file should contain two squares separated by a space. The output is in the format "To get from xx to yy takes n knight moves.".
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值