백준 7562 - 나이트의 이동 (파이썬)

Updated:

Answer

from sys import stdin
from collections import deque

input = stdin.readline

dx = [2, 2, -2, -2, 1, -1, 1, -1]
dy = [1, -1, 1, -1, 2, 2, -2, -2]

def bfs():
    global n, x1, y1, x2, y2
    queue = deque([(x1, y1)])
    visited = [[0] * n for _ in range(n)]

    while queue:
        x, y = queue.popleft()

        if x == x2 and y == y2:
            return visited[x][y]

        for i in range(8):
            nx = dx[i] + x
            ny = dy[i] + y

            if 0 <= nx < n and 0 <= ny < n:
                if visited[nx][ny] == 0:
                    visited[nx][ny] = visited[x][y] + 1
                    queue.append((nx, ny))

    return 0

for _ in range(int(input())):
    n = int(input())
    x1, y1 = map(int, input().split())
    x2, y2 = map(int, input().split())

    print(bfs())

Categories:

Updated: