解题思路:
注意事项:
参考代码:
from collections import deque
def knight_moves(n, start, end):
directions = [
(-2, -1), (-2, 1), (-1, -2), (-1, 2),
(1, -2), (1, 2), (2, -1), (2, 1)
]
queue = deque([(start, 0)])
visited = set([start]) # visited 是一个集合(set),用于记录已经访问过的位置。visited 初始时被设置为包含起始位置 start 的集合。
while queue:
position, steps = queue.popleft()
if position == end:
return steps
x, y = position
for dx, dy in directions:
new_x, new_y = x + dx, y + dy
if 0 <= new_x < n and 0 <= new_y < n and (new_x, new_y) not in visited:
queue.append(((new_x, new_y), steps + 1))
visited.add((new_x, new_y))
return -1 # 如果无法到达目标位置,则返回-1
# 读取输入
test_cases = int(input())
for _ in range(test_cases):
n = int(input())
start = tuple(map(int, input().split()))
end = tuple(map(int, input().split()))
# 调用函数计算最小步数
min_steps = knight_moves(n, start, end)
print(min_steps)
0.0分
0 人评分