BOJ - 7562 - 나이트의 이동

Updated:

import sys
from collections import deque

def BFS(I, startX, startY, endX, endY):

    maps = [[False] * I for _ in range(I)]

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

    Q = deque()
    Q.append((startX, startY, 0))


    while Q:
        x, y, time = Q.popleft()
        if x == endX and y == endY:
            return time

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

            if 0 <= nx < I and 0 <= ny < I:
                if maps[nx][ny] is False:
                    maps[nx][ny] = time + 1
                    Q.append((nx, ny, time + 1))

def solution():
    T = int(input())

    for _ in range(T):
        I = int(input())
        startX, startY = map(int, sys.stdin.readline().split())
        endX, endY = map(int, sys.stdin.readline().split())

        print(BFS(I, startX, startY, endX, endY))


solution()

https://www.acmicpc.net/problem/7562

Categories:

Updated:

Leave a comment