λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/boj

BOJ 7562 - λ‚˜μ΄νŠΈμ˜ 이동

by HandHand 2021. 3. 18.

문제

λ°±μ€€ 온라인 저지 - 7562번

풀이 κ³Όμ •

λ‚˜μ΄νŠΈκ°€ 이동할 수 μžˆλŠ” λ°©ν–₯을 톡해 λͺ©ν‘œ 지점에 λ„λ‹¬ν•˜λŠ” μ΅œμ†Œ 이동 횟수λ₯Ό μ°Ύμ•„μ£ΌλŠ” λ¬Έμ œμž…λ‹ˆλ‹€.
이동할 수 μžˆλŠ” λ°©ν–₯이 8κ°€μ§€λΌλŠ” 점을 μ œμ™Έν•˜λ©΄ 일반적인 BFS 탐색 ν’€μ΄λ²•μœΌλ‘œ ν•΄κ²°ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

μ½”λ“œ


import sys
from collections import deque


T = int(input())
test_case = []
for _ in range(T):
    L = int(input())
    cur = list(map(int, sys.stdin.readline().split()))
    goal = list(map(int, sys.stdin.readline().split()))
    test_case.append([L, cur, goal])


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


def bfs(L, start, goal):

    q = deque()
    visit = [[False] * L for _ in range(L)]

    visit[start[0]][start[1]] = True
    q.append((start[0], start[1], 0))

    while q:
        x, y, cost = q.popleft()
        if x == goal[0] and y == goal[1]:
            return cost

        for i in range(8):
            next_x, next_y = x + dx[i], y + dy[i]
            if 0 <= next_x < L and 0 <= next_y < L and not visit[next_x][next_y]:
                visit[next_x][next_y] = True
                q.append((next_x, next_y, cost + 1))


def solution():
    for case in test_case:
        print(bfs(case[0], case[1], case[2]))


solution()
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€