문제
풀이
코드
from collections import deque
import sys
input = sys.stdin.readline
dx = [-2, -2, -1, -1, 1, 1, 2, 2]
dy = [-1, 1, -2, 2, -2, 2, -1, 1]
def bfs(start_x, start_y, end_x, end_y):
queue = deque()
queue.append([start_x, start_y])
graph[start_x][start_y] = 1
while queue:
x, y = queue.popleft()
if x == end_x and y == end_y:
print(graph[end_x][end_y]-1)
return
for j in range(8):
nx = x + dx[j]
ny = y + dy[j]
if nx < 0 or ny < 0 or nx >= i or ny >= i:
continue
if graph[nx][ny] == 0:
queue.append([nx, ny])
graph[nx][ny] = graph[x][y] + 1
n = int(input())
for _ in range(n):
i = int(input())
start_x, start_y = map(int, input().split())
end_x, end_y = map(int, input().split())
graph = [[0] * i for _ in range(i)]
bfs(start_x, start_y, end_x, end_y)
결과
출처 & 깃허브
BOJ 7562
github