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

BOJ 10472 - μ‹­μžλ’€μ§‘κΈ°

by HandHand 2021. 4. 18.

문제

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

풀이 κ³Όμ •

λ³΄λ“œμ˜ μ΅œμ’… μƒνƒœκ°€ μ£Όμ–΄μ§ˆ λ•Œ, 초기 μƒνƒœμ—μ„œ ν•΄λ‹Ή λͺ©ν‘œ μƒνƒœμ— λ„λ‹¬ν•˜κΈ° μœ„ν•œ μ΅œμ†Œ μ‘°μž‘ 횟수λ₯Ό κ΅¬ν•˜λŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

이λ₯Ό μœ„ν•΄μ„œ BFS λ₯Ό μ΄μš©ν•΄ λ³΄λ“œμ˜ λͺ¨λ“  κ°€λŠ₯ν•œ μƒνƒœλ₯Ό μˆœνšŒν•΄μ€λ‹ˆλ‹€.
λ‹€λ§Œ μ€‘λ³΅λœ μƒνƒœ 순회λ₯Ό ν”Όν•˜κΈ° μœ„ν•΄μ„œ λ³΄λ“œκ°€ κ²€μ€μƒ‰μœΌλ‘œ μΉ ν•΄μ Έ μžˆμ„ 경우 1 둜, 그렇지 μ•Šμ„ 경우 0 으둜 λ³€ν™˜ν•˜μ—¬

μ΄μ§„μˆ˜λ₯Ό μƒμ„±ν•œ λ‹€μŒ, μ€‘λ³΅λœ μƒνƒœλ₯Ό κ²€μ¦ν•©λ‹ˆλ‹€.

μ½”λ“œ


import sys
import copy
from collections import deque


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


def convert_board(board, x, y):
    ret = copy.deepcopy(board)

    for i in range(5):
        nx, ny = x + dx[i], y + dy[i]
        if 0 <= nx < 3 and 0 <= ny < 3:
            ret[nx][ny] = '*' if ret[nx][ny] == '.' else '.'

    return ret


def convert_to_binary(board):
    binary_str = ''

    for x in range(3):
        for y in range(3):
            binary_str += '0' if board[x][y] == '.' else '1'

    return int(binary_str, 2)


def bfs(goal):
    time = 0
    init_board = [['.'] * 3 for _ in range(3)]
    visit = [0] * 1000

    q = deque([init_board])
    visit[convert_to_binary(init_board)] = 1

    while q:
        loop = len(q)
        for _ in range(loop):
            board = q.popleft()
            if board == goal:
                return time

            for row in range(3):
                for col in range(3):
                    next_board = convert_board(board, row, col)
                    binary_code = convert_to_binary(next_board)

                    if not visit[binary_code]:
                        q.append(next_board)
                        visit[binary_code] = 1

        time += 1


def solution(testcase):
    time = bfs(testcase)

    return time


if __name__ == '__main__':
    T = int(input())
    for _ in range(T):
        testcase = [list(sys.stdin.readline().strip()) for _ in range(3)]
        answer = solution(testcase)
        print(answer)
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€