Python)
import sys
from collections import deque
read = sys.stdin.readline
q = deque()
dx = [-2,-1,1,2,2,1,-1,-2]
dy = [1,2,2,1,-1,-2,-2,-1]
t = int(read().rstrip())
for _ in range(t):
l = int(read().rstrip())
x1, y1 = map(int, read().rstrip().split())
x2, y2 = map(int, read().rstrip().split())
# 체스판 만들기
arr = [[-1] * l for __ in range(l)]
# 시작점 넣기
q.append((x1, y1))
arr[x1][y1] = 0
while q:
x, y = q.popleft()
# 이동하고자 하는 칸에 도착함
if x == x2 and y == y2:
print(arr[x2][y2])
break
for k in range(8):
nx = x + dx[k]
ny = y + dy[k]
if nx < 0 or nx >= l or ny < 0 or ny >=l:
continue
if arr[nx][ny] == -1:
arr[nx][ny] = arr[x][y] + 1
q.append((nx,ny))
# 중간에 break로 인해 큐가 안 비워졌을 수 있음으로 비우기
while q:
q.pop()'백준 2 > 그래프' 카테고리의 다른 글
| [백준 13549] 숨바꼭질3 (C++/Python) (0) | 2023.07.04 |
|---|---|
| [백준 2573] 빙산 (C++/Python) (0) | 2023.06.29 |
| [백준 5014] 스타트링크 (C++/Python) (0) | 2023.04.05 |
| [백준 1926] 그림 (C++/Python) (0) | 2023.03.24 |
| [백준 2610] 회의준비 (Java) (0) | 2020.12.24 |