Algorithm Problems
[백준] [Python] 7562번 나이트의 이동 - BFS
WakaraNai
2021. 5. 11. 01:39
728x90
반응형
7562번: 나이트의 이동
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수
www.acmicpc.net
Python
import sys
from collections import deque
dx = [1,1,-1,-1,2,2,-2,-2]
dy = [2,-2,2,-2,1,-1,1,-1]
for _ in range(int(sys.stdin.readline().rstrip())):
l = int(sys.stdin.readline().rstrip())
board = [[0]*l for _ in range(l)]
now = list(map(int,sys.stdin.readline().split()))
dest = list(map(int,sys.stdin.readline().split()))
q = deque()
q.append(now)
while q:
pos = q.popleft()
if board[pos[0]][pos[1]] == 0:
board[pos[0]][pos[1]] = 1
for i in range(8):
nx = pos[0]+dx[i]
ny = pos[1]+dy[i]
if 0<=nx<l and 0<=ny<l:
if board[nx][ny]==0:
q.append([nx,ny])
board[nx][ny] = board[pos[0]][pos[1]]+1
print(board[dest[0]][dest[1]]-1)
728x90
반응형