알고리즘/dfs,bfs
[파이썬🐍] 백준 7562 : 나이트의 이동
코딩개미뚠뚠
2021. 5. 31. 20:12
반응형
from collections import deque
import sys
input = sys.stdin.readline
def bfs(sx,sy,ax,ay):
q = deque()
q.append([sx,sy])
s[sx][sy] = 1
while q:
a,b = q.popleft()
if (a == ax) and (b == ay):
return print(s[ax][ay]-1)
for i in range(8):
x = a + dx[i]
y = b + dy[i]
if 0 <= x < n and 0 <= y < n and s[x][y] == 0:
q.append([x,y])
s[x][y] = s[a][b] + 1
dx = [-1,-2,-2,-1,1,2,2,1]
dy = [2,1,-1,-2,-2,-1,1,2]
t = int(input())
for i in range(t):
n = int(input())
sx,sy = map(int,input().split()) #시작좌표
ax,ay = map(int,input().split()) #목표좌표
s = [[0]*n for i in range(n)]
bfs(sx,sy,ax,ay)
나이트의 이동의 특성을 고려해서 8개의 이동으로 dx, dy를 완성해준다.
반응형