内容中心

2026年热门的昆明泡沫包装箱精选厂家推荐-昆明官宝泡沫有限公司

To solve this problem, we need to determine the minimum number of steps a knight takes to move from one position to another on an infinite chessboard. A knight moves in an L-shape, which means it can move two squares in one direction and then one square perpendicular, or one square in one direction and two squares perpendicular (8 possible moves in total).

Approach

The optimal approach to solve this problem is using Breadth-First Search (BFS). BFS is suitable here because it explores all possible moves level by level, ensuring that the first time we reach the target position, it is via the shortest path (minimum steps).

  1. Initialization: Start from the given initial position and check if it is the target position (0 steps if true).
  2. BFS Queue: Use a queue to keep track of the current position and the number of steps taken to reach it.
  3. Visited Set: Maintain a set of visited positions to avoid revisiting and cycles.
  4. Explore Moves: For each position, generate all 8 possible knight moves. If any of these moves reaches the target, return the current step count plus one. Otherwise, add the new position to the queue if it hasn't been visited.

Solution Code

from collections import deque
import sys

def min_knight_steps(x1, y1, x2, y2):
    if x1 == x2 and y1 == y2:
        return 0

    visited = set()
    queue = deque()
    queue.append((x1, y1, 0))
    visited.add((x1, y1))

    moves = [(2, 1), (2, -1), (-2, 1), (-2, -1),
             (1, 2), (1, -2), (-1, 2), (-1, -2)]

    while queue:
        x, y, steps = queue.popleft()
        for dx, dy in moves:
            nx = x + dx
            ny = y + dy
            if nx == x2 and ny == y2:
                return steps + 1
            if (nx, ny) not in visited:
                visited.add((nx, ny))
                queue.append((nx, ny, steps + 1))

# Read input
x1, y1 = map(int, sys.stdin.readline().split())
x2, y2 = map(int, sys.stdin.readline().split())

# Compute and print the result
print(min_knight_steps(x1, y1, x2, y2))

Explanation

  • BFS Exploration: The BFS ensures that we explore all positions at the current step count before moving to positions that require more steps. This guarantees the shortest path.
  • Visited Set: This set prevents us from processing the same position multiple times, which saves time and avoids infinite loops.
  • Efficiency: The BFS runs in O(step^2) time complexity, where step is the minimum number of steps to reach the target. Since the knight's steps are limited (usually up to 4-5 steps for most cases), this approach is very efficient.

This solution handles all edge cases, including when the initial position is the target, when the target is one knight move away, and when the target requires multiple steps. It works for any valid input on an infinite chessboard.

昆明官宝泡沫有限公司

昆明官宝泡沫有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?