<λ¬Έμ λ§ν¬>
https://www.acmicpc.net/problem/17142
<νμ΄ μ λ΅>
1. μ°κ΅¬μ 2λ λ§€μ° μ μ¬νλ λΉνμ± λ°μ΄λ¬μ€μ μ²λ¦¬κ° μκ°λ³΄λ€ κΉλ€λ‘λ€
2. νμ±λ°μ΄λ¬μ€μ λ§λλ©΄ νμ± μνλ‘ λ³νλ '1'μ μ±μ§μ κ°μ§λ©΄μ, λμμ νμ° μκ°μλ μν₯μ λ―ΈμΉμ§ μμΌλ―λ‘ '0'μ μ±μ§μ κ°μ§κ² λλ€.
3. μ¬λ¬κ°μ§ λ°©λ²μ΄ μκ² μ§λ§ λ κ°μ κ²½μ°λ λΉνμ± -> νμ± λ°μ΄λ¬μ€μ μ’νλ₯Ό μ μ₯νλ©΄μ νμνλ€κ° λ§μ§λ§μ 0μΌλ‘ μ΄κΈ°νν΄μ€μΌλ‘μ¨ νμ° μκ° κ³μ°μ μν₯μ μ λ―ΈμΉλλ‘ νλ€.
<μ λ΅ μ½λ>
from collections import deque
from itertools import combinations
import sys, os, io, atexit
input = lambda: sys.stdin.readline().rstrip('\r\n')
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
atexit.register(lambda: os.write(1, stdout.getvalue()))
# 220924 17142 μ°κ΅¬μ 3
# μ λ΅μ½λ
# λΈν νμ λ°©ν₯ μ€μ
dr = [-1, 1, 0, 0]
dc = [0, 0, -1, 1]
# λ°μ΄λ¬μ€ νμ° bfs
def bfs(queue):
# νμ± μνλ‘ λ³ν λΉνμ± λ°μ΄λ¬μ€λ₯Ό λ΄μ 리μ€νΈ
activated = []
while queue:
r, c = queue.popleft()
for i in range(4):
nr = r + dr[i]
nc = c + dc[i]
if 0 <= nr < N and 0 <= nc < N:
# λΉ κ³΅κ°μ΄λ©΄ λ°μ΄λ¬μ€ νμ°
if arr_copy[nr][nc] == -10:
arr_copy[nr][nc] = arr_copy[r][c] + 1
queue.append((nr, nc))
# λΉνμ± λ°μ΄λ¬μ€μΌ κ²½μ° μΌλ¨ λ°μ΄λ¬μ€ νμ° ν 리μ€νΈμ λ΄μμ€λ€.
if arr_copy[nr][nc] == -2:
arr_copy[nr][nc] = arr_copy[r][c] + 1
activated.append((nr, nc))
queue.append((nr, nc))
# λΉ κ³΅κ°μ΄ λ¨μμμ κ²½μ°
for r in range(N):
for c in range(N):
if arr_copy[r][c] == -10:
return sys.maxsize
# λΉνμ± -> νμ± λ°μ΄λ¬μ€λ€μ 0μΌλ‘ μ΄κΈ°ν μμΌμ€μ νμ° μκ°μ κ²μ°μ μν₯μ μ λ―ΈμΉλλ‘ νλ€
for row, col in activated:
arr_copy[row][col] = 0
# νμ° μκ° λ°ν
return max(map(max, arr_copy))
# N: μ°κ΅¬μμ ν¬κΈ°, M: λ°μ΄λ¬μ€μ κ°μ
N, M = map(int, input().split())
# arr: μ°κ΅¬μ μν
arr = [list(map(int, input().split())) for _ in range(N)]
# virus: λ°μ΄λ¬μ€λ₯Ό λμ μμΉ
virus = []
# λΉ κ³΅κ°μ -10μΌλ‘ μ΄κΈ°νν΄μ£Όκ³ λ°μ΄λ¬μ€μ μμΉλ₯Ό λ΄μμ€λ€.
for r in range(N):
for c in range(N):
if arr[r][c] == 0:
arr[r][c] = -10
if arr[r][c] == 1:
arr[r][c] = -1
if arr[r][c] == 2:
arr[r][c] = -2
virus.append((r, c))
# ans: λ°μ΄λ¬μ€ μ 체 νμ° μκ° (μΆ©λΆν ν° κ°μΌλ‘ μ΄κΈ°ν)
ans = sys.maxsize
# λ°μ΄λ¬μ€λ₯Ό λμ μμΉλ₯Ό κ³ λ₯Έλ€.
for comb in combinations(virus, M):
# arr_copy: bfs νμμ© λ°°μ΄ λ³΅μ¬λ³Έ
arr_copy = [arr[i][:] for i in range(N)]
# λ°μ΄λ¬μ€μ μμΉ νμ λ΄μμ£ΌκΈ°
queue = deque()
for loc in comb:
queue.append(loc)
r, c = loc
arr_copy[r][c] = 0
# μ λ΅ κ°±μ ν΄κ°λ©΄μ bfs νμ
ans = min(bfs(queue), ans)
# λ€ νμ° μν€μ§ λͺ»ν κ²½μ° -1 μΆλ ₯
if ans == sys.maxsize:
print(-1)
# μ λ΅ μΆλ ₯
else:
print(ans)
'β Problem_Solving > λ°±μ€' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
[λ°±μ€] 12100 2048 (Easy) (Python/νμ΄μ¬) (1) | 2022.10.11 |
---|---|
[λ°±μ€] 18405 κ²½μμ μ μΌ (Python/νμ΄μ¬) (0) | 2022.10.10 |
[λ°±μ€] 1766 λ¬Έμ μ§ (Python/νμ΄μ¬) (0) | 2022.10.06 |
[λ°±μ€] 1662 μμΆ (Python/νμ΄μ¬) (1) | 2022.10.05 |
[λ°±μ€] 20057 λ§λ²μ¬ μμ΄μ ν λ€μ΄λ (Python/νμ΄μ¬) (0) | 2022.10.04 |
λκΈ