알고리즘/백준

백준 7564: 나이트의 이동 (Python)

sssbin 2022. 2. 3. 19:58

 

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

 

7562번: 나이트의 이동

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

www.acmicpc.net

 

from collections import deque

t = int(input())

def bfs(x1, y1, x2, y2):
    queue = deque()
    queue.append([x1, y1])

    chess[x1][y1] = 1

    dx = [-1, -2, -2, -1, 1, 2, 2, 1]
    dy = [-2, -1, 1, 2, 2, 1, -1, -2]

    while queue:
        qx, qy = queue.popleft()

        if qx == x2 and qy == y2:
            print(chess[qx][qy] - 1)
            break

        for i in range(8):
            x = qx + dx[i]
            y = qy + dy[i]

            if x < 0 or x >= n or y < 0 or y >= n:
                continue

            if chess[x][y] == 0:
                queue.append([x, y])
                chess[x][y] = chess[qx][qy] + 1


for i in range(t):
    n = int(input())
    chess = [[0 for _ in range(n)] for _ in range(n)]
    start = list(map(int, input().split()))
    end = list(map(int, input().split()))
    bfs(start[0], start[1], end[0], end[1])

 

미로 탐색 문제랑 거의 똑같다

좌표 이동 배열만 상하좌우가 아닌 그림에 나와있는 좌표로 해주면 된다!

된 거 같은데 계속 답이 안 나와서 헤매고 있었는데

큐를 함수 바깥에 선언해서 큐에 전에 썼던 좌표들이 남아있어서 그런거였다,,,