river_mseok   2년 전

import sys
from collections import deque

input = sys.stdin.readline
S = tuple(map(int, input().split()))
T = tuple(map(int, input().split()))
dir = [(3,2), (3,-2), (-3,2), (-3,-2), (2,3), (-2,3), (2,-3), (-2,-3)]

q = deque()
sy, sx = S
q.append((sy, sx, 0))
ans = float("inf")
Visited = [[False] * 9 for _ in range(10)]
Visited[sy][sx] = True

while q:
y, x, cnt = q.popleft()
for dy, dx in dir:
ny, nx = y + dy, x + dx
if (ny, nx) == T:
ans = min(ans, cnt + 1)
continue
if 0 <= ny <= 9 and 0 <= nx <= 8 and not Visited[ny][nx]:
Visited[ny][nx] = True
q.append((ny, nx, cnt + 1))

if ans == float("inf"):
print(-1)
else:
print(ans)

j213h   2년 전

0 0

2 1

입력이 위와 같은 경우, 5가 나와야 하는데 3을 출력합니다.

댓글을 작성하려면 로그인해야 합니다.