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

BOJ 14923 - 미둜 νƒˆμΆœ

by HandHand 2021. 3. 18.

문제

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

풀이 κ³Όμ •

μ‹œμž‘ μ§€μ μ—μ„œ λͺ©ν‘œ 지점에 λ„λ‹¬ν•˜λŠ” μ΅œλ‹¨ 경둜λ₯Ό μ°ΎλŠ” BFS λ¬Έμ œμž…λ‹ˆλ‹€.

단 벽이 μ‘΄μž¬ν•  경우 1νšŒμ— ν•œν•΄μ„œ 벽을 λΆ€μˆ˜κ³  이동할 수 있기 λ•Œλ¬Έμ— μƒνƒœ 곡간을 λ‹€μŒκ³Ό 같이 μ •μ˜ν•©λ‹ˆλ‹€.


visit[x][y][magic] : (x, y) 지점에 남은 λ§ˆλ²•μ˜ 횟수 magic 을 μ΄μš©ν•˜μ—¬ 도달 ν•œ κ²½μš°κ°€ μžˆλŠ”μ§€


이후 λͺ©ν‘œ 지점에 λ„λ‹¬ν•˜λ©΄ 거리 λ°”μš©μ„ λ°˜ν™˜ν•˜λ©΄ λ©λ‹ˆλ‹€.

μ½”λ“œ


import sys
from collections import deque

N, M = list(map(int, sys.stdin.readline().split()))
Hx, Hy = list(map(int, sys.stdin.readline().split()))
Ex, Ey = list(map(int, sys.stdin.readline().split()))
board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]

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


def bfs():
    q = deque()
    visit = [[[0] * 2 for _ in range(M)] for _ in range(N)]

    q.append([Hx - 1, Hy - 1, 1, 0])
    visit[Hx - 1][Hy - 1][1] = 1

    while q:
        x, y, magic, cost = q.popleft()

        if [x, y] == [Ex - 1, Ey - 1]:
            return cost

        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]

            if 0 <= nx < N and 0 <= ny < M:
                if visit[nx][ny][magic]:
                    continue

                if magic and board[nx][ny]:
                    visit[nx][ny][0] = 1
                    q.append([nx, ny, 0, cost + 1])
                elif not board[nx][ny]:
                    visit[nx][ny][magic] = 1
                    q.append([nx, ny, magic, cost + 1])

    return -1


def solution():
    answer = bfs()

    return answer


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

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

BOJ 2096 - λ‚΄λ €κ°€κΈ°  (0) 2021.03.18
BOJ 14716 - ν˜„μˆ˜λ§‰  (0) 2021.03.18
BOJ 17406 - λ°°μ—΄ 돌리기 4  (0) 2021.03.18
BOJ 1543 - λ¬Έμ„œ 검색  (0) 2021.03.18
BOJ 11403 - 경둜 μ°ΎκΈ°  (0) 2021.03.18

πŸ’¬ λŒ“κΈ€