본문 바로가기
알고리즘/DFS, BFS

[백준 -실버2] 7562번 나이트의 이동

by 호리미 2022. 1. 23.

https://www.acmicpc.net/problem/7562

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net

<내 코드>

- 상,하,좌,우 이동하는 문제와 다르게 나이트의 이동방향에 따라 8가지 방향으로 dx, dy를 설정해주었다.

- bfs 함수에서 목표로 하는 좌표가 나오면 break로 함수 종료

- 이동의 최소값을 구해야하기 때문에 bfs를 수행하면서 1씩 더해주어 이동 횟수를 파악하였다.

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(x,y):
    queue = deque()
    queue.append((x,y))
    while queue:
        x,y = queue.popleft()
        if x == x_target and y== y_target:
            break
        for i in range(8):
            nx = x+ dx[i]
            ny = y + dy[i]
            if 0<=nx<n and 0<=ny<n and graph[nx][ny]==0:
                queue.append((nx,ny))
                graph[nx][ny] = graph[x][y] +1
            
t = int(input())
for _ in range(t):
    n = int(input())
    graph = [[0]*n for _ in range(n)]
    now_x, now_y = map(int, input().split())
    x_target, y_target = map(int, input().split())
    bfs(now_x, now_y) 
            
    print(graph[x_target][y_target])