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

BOJ 5980 - Corn Maze

by HandHand 2021. 6. 7.

문제

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

풀이 κ³Όμ •

μ‹œμž‘μ§€μ μ—μ„œ λͺ©ν‘œμ§€μ μ— λ„λ‹¬ν•˜κΈ° μœ„ν•œ μ΅œμ†Œ 이동 횟수λ₯Ό κ΅¬ν•˜λŠ” BFS λ¬Έμ œμž…λ‹ˆλ‹€.

μ—¬κΈ°μ„œ μ£Όμ˜ν•  점은 νŠΉμ • μ§€μ κ°„μ˜ μ–‘λ°©ν–₯ ν¬νƒˆμ΄ μ‘΄μž¬ν•œλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€.

각각의 ν¬νƒˆμ€ λŒ€λ¬Έμž μ•ŒνŒŒλ²³μœΌλ‘œ 제곡되기 λ•Œλ¬Έμ— ν•΄μ‹œ ν…Œμ΄λΈ” 을 μ΄μš©ν•΄μ„œ 각 ν¬νƒˆμ˜ 정보λ₯Ό κ΄€λ¦¬ν•©λ‹ˆλ‹€.

λ˜ν•œ 쀑볡 방문을 λ°©μ§€ν•˜κΈ° μœ„ν•΄μ„œ visit 을 체크할 λ•Œ ν¬νƒˆμ˜ μœ„μΉ˜λŠ” 쀑볡 방문을 ν—ˆμš©ν•΄μ•Ό ν•œλ‹€λŠ” 점에 μ£Όμ˜ν•©λ‹ˆλ‹€.

μ΄λ ‡κ²Œ ν•˜μ§€ μ•ŠμœΌλ©΄ ν¬νƒˆμ„ ν•œλ²ˆλ°–μ— μ‚¬μš©ν•˜μ§€ λͺ»ν•˜λŠ” 상황이 λ°œμƒν•˜μ—¬ ν•„μš”ν•  λ•Œ μ‚¬μš©ν•  수 μ—†κΈ° λ•Œλ¬Έμž…λ‹ˆλ‹€.

μ΄λ‘œμΈν•΄ λ‹€μŒκ³Ό 같은 μ˜ˆμ‹œμ—μ„œ λ¬Έμ œκ°€ λ°œμƒν•  수 μžˆμŠ΅λ‹ˆλ‹€.

######
#.WB##
#.####
=B@W##
######

μ½”λ“œ


import sys
from collections import deque

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

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


def pre_processing():
    start, goal = [], []
    slides = {}

    for x in range(N):
        for y in range(M):
            if board[x][y] == '@':
                start = [x, y]
            if board[x][y] == '=':
                goal = [x, y]
            if 'A' <= board[x][y] <= 'Z':
                if board[x][y] not in slides:
                    slides[board[x][y]] = [[x, y]]
                else:
                    slides[board[x][y]].append([x, y])

    return start, goal, slides


def bfs(start, goal, slides):
    q = deque()
    visit = [[0] * M for _ in range(N)]

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

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

        if [x, y] == goal:
            return cost

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

            if 0 <= nx < N and 0 <= ny < M:
                if not board[nx][ny] == '#' and not visit[nx][ny]:
                    if 'A' <= board[nx][ny] <= 'Z':
                        slide = slides[board[nx][ny]]

                        if [nx, ny] == slide[0]:
                            q.append([*slide[1], cost + 1])
                        else:
                            q.append([*slide[0], cost + 1])
                    else:
                        if not visit[nx][ny]:
                            visit[nx][ny] = 1
                            q.append([nx, ny, cost + 1])


def solution():
    start, goal, slides = pre_processing()
    answer = bfs(start, goal, slides)

    return answer


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

πŸ’¬ λŒ“κΈ€