Knight Moves BFS

骑士周游问题BFS解法
部署运行你感兴趣的模型镜像

又一次做到这一题了, 记得第一次做的时候大笑, 理解成DFS。(其实当时没有DFS || BFS的概念), 这一次做这题信手捏来。

#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;

#define DIRECTION_N 8
#define MAP_SIZE 8
#define REACHED 1
#define UNREACHED 0

struct Node {
	int x, y;
	int steps;
};

const int direction[DIRECTION_N][2] = {{1,2}, {-1,2}, {1,-2}, {-1,-2}, {2,1}, {-2,1}, {2,-1}, {-2,-1}};
int map[MAP_SIZE][MAP_SIZE];
Node end;

int BFS(Node);
bool ok(Node);

int main()
{
	Node star;

	char x1, x2, y1, y2;
	while (scanf("%c%c %c%c%*c", &x1, &y1, &x2, &y2) != EOF) {
		memset(map, UNREACHED, sizeof(map));		//全地图标记未到达

		star.x = (int)(x1 - 'a');	
		star.y = (int)(y1 - '1');
		star.steps = 0;
		end.x = (int)(x2 - 'a');
		end.y = (int)(y2 - '1');

		printf("To get from %c%c to %c%c takes %d knight moves.\n", x1, y1, x2, y2, BFS(star));
	}

	return 0;
}

//广搜索
int BFS(Node star)
{
	queue<Node> que;	
	que.push(star);

	while (!que.empty()) {
		Node root = que.front();
		que.pop();

		if (root.x == end.x && root.y == end.y) {		//出口
			return root.steps;
		}

		for (int i = 0; i < DIRECTION_N; i++) {
			Node child = root;

			child.x += direction[i][0];
			child.y += direction[i][1];
			child.steps++;

			if (ok(child)) {
				map[child.x][child.y] = REACHED;
				que.push(child);
			}
		}
	}

	printf("no way\n");
	return 0;
}

//判断行走是否合法
bool ok(Node now)
{
	if (now.x >= 0 && now.x < MAP_SIZE && now.y >= 0 && now.y < MAP_SIZE && map[now.x][now.y] == UNREACHED) {
		return true;
	}

	return false;
}


您可能感兴趣的与本文相关的镜像

Qwen3-8B

Qwen3-8B

文本生成
Qwen3

Qwen3 是 Qwen 系列中的最新一代大型语言模型,提供了一整套密集型和专家混合(MoE)模型。基于广泛的训练,Qwen3 在推理、指令执行、代理能力和多语言支持方面取得了突破性进展

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

余额充值