λ¬Έμ
λ°±μ€ μ¨λΌμΈ μ μ§ - 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)
λ°μν
'π algorithm > boj' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
BOJ 1240 - λ Έλμ¬μ΄μ 거리 (0) | 2021.06.07 |
---|---|
BOJ 11265 - λλμ§ μλ νν° (0) | 2021.06.04 |
BOJ 13908 - λΉλ°λ²νΈ (0) | 2021.04.13 |
BOJ 14940 - μ¬μ΄ μ΅λ¨κ±°λ¦¬ (0) | 2021.04.13 |
BOJ 16441 - μκΈ°λΌμ§μ λλ (0) | 2021.04.13 |
π¬ λκΈ