[BOJ] 7562. 나이트의 이동

2025. 7. 23. 14:07·BOJ

📌 문제 제목

문제 링크: BOJ 7562

🗒️ 문제 설명

체스판 위에 한 나이트가 놓여져 있다. 나이트가 이동하려고 하는 칸이 주어진다.

나이트는 몇 번 움직이면 이 칸으로 이동할 수 있을까?


💡 문제 해결 아이디어

  • 나이트의 이동 direction을 정의
  • dist 배열을 만들어서 이동한 적 없는 좌표에 대해서만 움직인다.

⌛️ 시간 복잡도

  • O(T x L^2)

✅ 최종 코드

import sys
from collections import deque
input = sys.stdin.readline

T = int(input().strip())

direction = [(-2, 1), (-1, 2), (1, 2), (2, 1),
             (2, -1), (1, -2), (-1, -2), (-2, -1)]


def bfs(s_x, s_y, e_x, e_y, dist):
    queue = deque([(s_x, s_y)])
    while queue:
        xp, yp = queue.popleft()
        if xp == e_x and yp == e_y:
            break
        for dx, dy in direction:
            nx, ny = xp + dx, yp + dy
            if not (0 <= nx < L and 0 <= ny < L):
                continue
            if dist[nx][ny] == -1:
                queue.append((nx, ny))
                dist[nx][ny] = dist[xp][yp] + 1
    return dist[e_x][e_y]


for _ in range(T):
    L = int(input().strip())

    s_x, s_y = map(int, input().split())
    e_x, e_y = map(int, input().split())

    dist = [[-1] * L for _ in range(L)]
    dist[s_x][s_y] = 0
    print(bfs(s_x, s_y, e_x, e_y, dist))

'BOJ' 카테고리의 다른 글

[BOJ] 14500. 테트로미노  (1) 2025.07.24
[BOJ] 2583. 영역 구하기  (0) 2025.07.23
[BOJ] 7569. 토마토  (0) 2025.07.23
[BOJ] 10026. 적록색약  (0) 2025.07.23
[BOJ] 1012. 유기농 배추  (0) 2025.07.23
'BOJ' 카테고리의 다른 글
  • [BOJ] 14500. 테트로미노
  • [BOJ] 2583. 영역 구하기
  • [BOJ] 7569. 토마토
  • [BOJ] 10026. 적록색약
rubato.dev
rubato.dev
  • rubato.dev
    rubato.dev
    rubato.dev
  • 전체
    오늘
    어제
    • 분류 전체보기 (33) N
      • BOJ (28) N
      • 알고리즘 (4) N
      • TIL (0)
      • Project (1) N
  • 인기 글

  • 태그

    Project
    Algorithm
    Zelda
    스택
    DFS
    stack
    PriorityQueue
    backtracking
    BOJ
    dp
    투 포인터
    PYTHON
    Next.js
    BFS
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
rubato.dev
[BOJ] 7562. 나이트의 이동
상단으로

티스토리툴바