[백준 7562] 나이트의 이동(python)

최제원·2024년 7월 24일

algorithm

목록 보기
5/12
post-thumbnail

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

문제 이해

시작점 (N, M)에서 도착점 (Y, K)까지 갈 수 있는 경로중 가장 짧은 경로를 추출하면 된다

문제 포인트

  1. (N,M) 자신의 좌표로 부터 시작한다
  2. 탐색이 모두 완료되면 이동한 위치만큼 print()

제출 코드

import sys
from collections import deque

input = sys.stdin.readline

N = int(input().strip())

for t in range(N):
    I = int(input().strip())
    y, x = map(int, input().strip().split())
    goal_y, goal_x = map(int, input().strip().split())

    if y == goal_y and x == goal_x:
        print(0)
        continue

    visited = [[False] * I for _ in range(I)]

    visited[y][x] = True
    queue = deque()
    queue.append((y, x, 1))

    ny = [-2, -2, +2, +2, -1, -1, +1, +1]
    nx = [-1, +1, -1, +1, -2, +2, -2, +2]

    found = False

    while queue:
        cur_y, cur_x, cur_point = queue.popleft()

        for i in range(8):
            next_y = cur_y + ny[i]
            next_x = cur_x + nx[i]

            if next_y == goal_y and next_x == goal_x:
                print(cur_point)
                found = True
                break

            if 0 <= next_x < I and 0 <= next_y < I:
                if not visited[next_y][next_x]:
                    visited[next_y][next_x] = True
                    queue.append((next_y, next_x, cur_point + 1))
        if found:
            break

백준 입력 받는거 조금 헷갈림.. 그것 때문에 런타임 에러 떠서 고생 좀 했음..

profile
Why & How

0개의 댓글