【bfs】Knight Moves

【题目描述】

输入nn代表有个n×nn×n的棋盘,输入开始位置的坐标和结束位置的坐标,问一个骑士朝棋盘的八个方向走马字步,从开始坐标到结束坐标可以经过多少步。

【输入】

首先输入一个nn,表示测试样例的个数。

每个测试样例有三行。

第一行是棋盘的大小L(4L300)L(4≤L≤300);

第二行和第三行分别表示马的起始位置和目标位置(0..L1)(0..L−1)。

 

【输出】

马移动的最小步数,起始位置和目标位置相同时输出00。

【输入样例】

3
8
0 0
7 0
100
0 0
30 50
10
1 1
1 1

【输出样例】

5
28
0

【思路】:简单的bfs求最优解,主要是注意八个方向

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#include<string>
#include<cstring>
using namespace std;
const int maxn=999999999;
const int minn=-999999999;
inline int read() {
    char c = getchar();
    int x = 0, f = 1;
    while(c < '0' || c > '9') {
        if(c == '-') f = -1;
        c = getchar();
    }
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
//马移动的最小步数,起始位置和目标位置相同时输出0。
/*
首先输入一个n,表示测试样例的个数。
每个测试样例有三行。
第一行是棋盘的大小L(4≤L≤300);
第二行和第三行分别表示马的起始位置和目标位置(0..L?1)。
*/
struct node {
    int x,y,setp;
};
int bx,by,visit[410][410],sx,sy,n;
int dir[8][2]= {{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}};
int main() {
    int N;
    cin>>N;
pyyyyyy:
    while(N--) {
        cin>>n;
        for(int i=1; i<=n; ++i) {
            for(int j=1; j<=n; ++j) {
                visit[i][j]=0;
            }

        }
        cin>>bx>>by;
        cin>>sx>>sy;
        if(bx==sx&&by==sy) {
            cout<<0<<endl;
        }
        queue<node>q;
        visit[bx][by]=1;
        q.push((node) {
            bx,by,1
        });
        while(!q.empty() ) {
            node p=q.front();
            q.pop();
            for(int i=0; i<8; ++i) {
                int px=p.x +dir[i][0];
                int py=p.y +dir[i][1];
                if(px==sx&&py==sy) {
                    cout<<p.setp<<'\n';
                    goto pyyyyyy;
                }
                if(px >0&&px<=n&&py>0&&py<=n&&!visit[px][py]) {
                    visit[px][py]=1;
                    node kkk;
                    kkk.x=px;
                    kkk.y=py;
                    kkk.setp=p.setp+1;
                    q.push(kkk);
                }
            }
        }
    }
    return 0;
}

 





转载于:https://www.cnblogs.com/pyyyyyy/p/10733764.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值