https://www.acmicpc.net/problem/7562
7562번: 나이트의 이동
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수
www.acmicpc.net
from collections import deque
t = int(input())
dx = [-1,-2,-2,-1,1,2,2,1]
dy = [-2,-1,1,2,2,1,-1,-2]
def bfs(x,y,target_x,target_y):
if x==target_x and y==target_y:
return 0
q = deque()
q.append((x,y,0))
while q:
x, y, count = q.popleft()
for i in range(8):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < l and 0 <= ny < l and data[nx][ny] == 0:
data[nx][ny] = 1
if nx == target_x and ny == target_y:
return count+1
else:
q.append((nx, ny, count+1))
for _ in range(t):
l = int(input())
data = [[0]*l for _ in range(l)]
a,b = map(int,input().split())
data[a][b] = 1
target_x,target_y = map(int,input().split())
print(bfs(a,b,target_x,target_y))
'알고리즘' 카테고리의 다른 글
백준 17135번 : 캐슬 디펜스 (Python) (0) | 2021.01.25 |
---|---|
백준 2573번 : 빙산 (python) (0) | 2021.01.20 |
백준 1012번 : 유기농 배추(python) (0) | 2021.01.05 |
백준 2178번 : 미로 탐색(python) (0) | 2021.01.05 |
백준 1926번 : 그림(python) (0) | 2021.01.05 |