알고리즘/Python

[백준/Python] 7562번 : 나이트의 이동

_SIHA_ 2022. 4. 14. 23:08

📖  문제 링크

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

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net

 

  최종 코드

from collections import deque

def bfs():
    
    while check:
        x, y = check.popleft()
        if x == xd and y == yd:
            return board[x][y]
        for i in range(len(dx)):
            nx = x+dx[i]
            ny = y+dy[i]     
            if 0<=nx<n and 0<=ny<n and board[nx][ny] == 0:
            	board[nx][ny] = board[x][y] + 1
                check.append([nx, ny])
            
                

t = int(input())

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

for i in range(t):
    n = int(input())
    board = [[0]*n for _ in range(n)]
    x, y = map(int, input().split())
    xd, yd = map(int, input().split())
    check = deque()
    check.append([x, y])
    print(bfs())