Knight Moves (BFS)

Background
Mr Somurolov, fabulous chess-gamer indeed, asserts that no one else but him can move knights from one position to another so fast. Can you beat him?
The Problem
Your task is to write a program to calculate the minimum number of moves needed for a knight to reach one point from another, so that you have the chance to be faster than Somurolov.
For people not familiar with chess, the possible knight moves are shown in Figure 1.
                                              

Input
The input begins with the number n of scenarios on a single line by itself.
Next follow n scenarios. Each scenario consists of three lines containing integer numbers. The first line specifies the length l of a side of the chess board (4 <= l <= 300). The entire board has size l * l. The second and third line contain pair of integers {0, ..., l-1}*{0, ..., l-1} specifying the starting and ending position of the knight on the board. The integers are separated by a single blank. You can assume that the positions are valid positions on the chess board of that scenario.
Output
For each scenario of the input you have to calculate the minimal amount of knight moves which are necessary to move from the starting point to the ending point. If starting point and ending point are equal,distance is zero. The distance must be written on a single line.
Sample Input
3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1
Sample Output
5
28

0




BFS超级大水题

AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<cstdlib>
using namespace std;
int a[305][305];
int n,startx,starty,endx,endy,cnt,ans;
int dir[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}};
int vis[305][305]={0};
struct NODE{
    int x,y,d;
};
queue<NODE> q;
int bfs(int i,int j){
    vis[i][j]=1;
    NODE fir;
    fir.x=i;
    fir.y=j;
    fir.d=0;
    q.push(fir);
    while(!q.empty()){
        fir=q.front();
        q.pop();
        for(int i=0;i<8;i++){
            NODE tmp;
            tmp.x=fir.x+dir[i][0];
            tmp.y=fir.y+dir[i][1];
            if(tmp.x<0||tmp.y<0||tmp.x>=n||tmp.y>=n||vis[tmp.x][tmp.y])continue;
            else{
                vis[tmp.x][tmp.y]=1;
                tmp.d=fir.d+1;
                if(tmp.x==endx&&tmp.y==endy)
                    return tmp.d;
            }
            q.push(tmp);
        }
    }
}
int main()
{
    int t,x,y;
    scanf("%d",&t);
    while(t--){
        while(!q.empty())
        q.pop();
        memset(vis,0,sizeof(vis));
        scanf("%d",&n);
        scanf("%d%d",&startx,&starty);
        scanf("%d%d",&endx,&endy);
        if(startx==endx&&starty==endy){
            printf("0\n");
            continue;
        }
        printf("%d\n",bfs(startx,starty));
    }
    return 0;
}


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、付费专栏及课程。

余额充值