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

BOJ 16509 - μž₯κ΅°

by HandHand 2021. 3. 3.

문제

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

풀이 κ³Όμ •

상 이 움직일 수 μžˆλŠ” 방법을 κ³ λ €ν•˜μ—¬ μ™• μ—κ²Œ 도달 κ°€λŠ₯ν•œ μ΅œμ†Œμ‹œκ°„μ„ κ΅¬ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

λ¬Έμ œμ— μ œμ‹œλœ λ°©λ²•μœΌλ‘œ 상 을 BFS λ₯Ό μ΄μš©ν•΄ μ΅œμ†Œμ‹œκ°„μ„ ꡬ할 수 있으며 μ΄λ•Œ μ£Όμ˜ν•  점은
μƒμ˜ 이동 κ²½λ‘œκ°€ 격자λ₯Ό λ²—μ–΄λ‚˜κ±°λ‚˜ λ‹€λ₯Έ 물체가 있으면 μ•ˆλœλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€.

λ”°λΌμ„œ κ²½λ‘œμƒμ˜ λͺ¨λ“  지점을 ν™•μΈν•˜λŠ” check_path ν•¨μˆ˜λ₯Ό κ΅¬ν˜„ν•˜κ³  λ§Œμ•½ 톡과할 κ²½μš°μ—λ§Œ
ν•΄λ‹Ή μ§€μ μœΌλ‘œ 탐색을 μ΄μ–΄κ°€λŠ” λ°©λ²•μœΌλ‘œ κ΅¬ν˜„ν–ˆμŠ΅λ‹ˆλ‹€.

μ½”λ“œ


import sys
from collections import deque

sang = list(map(int, sys.stdin.readline().split()))
king = list(map(int, sys.stdin.readline().split()))


path_finder = {
    0: [[-1, 0], [-1, -1], [-1, -1]],
    1: [[-1, 0], [-1, 1], [-1, 1]],
    2: [[0, 1], [-1, 1], [-1, 1]],
    3: [[0, 1], [1, 1], [1, 1]],
    4: [[1, 0], [1, 1], [1, 1]],
    5: [[1, 0], [1, -1], [1, -1]],
    6: [[0, -1], [1, -1], [1, -1]],
    7: [[0, -1], [-1, -1], [-1, -1]],
}


def check_path(x, y, i):
    for idx, [dx, dy] in enumerate(path_finder[i]):
        x, y = x + dx, y + dy
        if x < 0 or x > 9 or y < 0 or y > 8:
            return [False, None]
        elif idx != 2 and [x, y] == king:
            return [False, None]

    return [True, [x, y]]


def bfs():
    visit = [[0] * 9 for _ in range(10)]
    q = deque()

    visit[sang[0]][sang[1]] = 1
    q.append([*sang, 0])

    while q:
        x, y, cost = q.popleft()
        if [x, y] == king:
            return cost

        for i in range(8):
            is_reachable, next = check_path(x, y, i)
            if is_reachable:
                nx, ny = next
                if not visit[nx][ny]:
                    visit[nx][ny] = 1
                    q.append([nx, ny, cost + 1])

    return -1


def solution():
    answer = bfs()

    return answer


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

'πŸƒ algorithm > boj' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

BOJ 19941 - 햄버거 λΆ„λ°°  (0) 2021.03.08
BOJ 16469 - μ†Œλ…„ 점프  (0) 2021.03.05
BOJ 13565 - 침투  (0) 2021.03.05
BOJ 1105 - νŒ”  (0) 2021.03.03
BOJ 3190 - λ±€  (0) 2021.03.01

πŸ’¬ λŒ“κΈ€