π¦₯ μ½ν
/BAEKJOON
[BAEKJOON python] 17142_μ°κ΅¬μ 3
μ§μ§μνμΉ΄
2023. 4. 5. 23:29
728x90
λ°μν
μ°κ΅¬μ 3
λ°μ΄λ¬μ€λ νμ± μνμ λΉνμ± μν
κ°μ₯ μ²μμ λͺ¨λ λ°μ΄λ¬μ€λ λΉνμ± μν
νμ± μνμΈ λ°μ΄λ¬μ€λ μνμ’μ°λ‘ μΈμ ν λͺ¨λ λΉ μΉΈμΌλ‘ λμμ 볡μ λλ©°, 1μ΄κ° κ±Έλ¦Ό
μ°κ΅¬μμ λ°μ΄λ¬μ€ Mκ°λ₯Ό νμ± μνλ‘ λ³κ²½νλ €κ³ ν¨
μ°κ΅¬μλ ν¬κΈ°κ° N×NμΈ μ μ¬κ°ν (1×1 ν¬κΈ°μ μ μ¬κ°νμΌλ‘ λλ¨)
μ°κ΅¬μλ 0μ λΉ μΉΈ, 1μ λ²½, 2λ λ°μ΄λ¬μ€μ μμΉ
νμ± λ°μ΄λ¬μ€κ° λΉνμ± λ°μ΄λ¬μ€κ° μλ μΉΈμΌλ‘ κ°λ©΄ λΉνμ± λ°μ΄λ¬μ€κ° νμ±μΌλ‘ λ³ν¨
μ°κ΅¬μμ μνκ° μ£Όμ΄μ‘μ λ, λͺ¨λ λΉ μΉΈμ λ°μ΄λ¬μ€λ₯Ό νΌλ¨λ¦¬λ μ΅μ μκ° κ΅¬ν
λ°μ΄λ¬μ€λ₯Ό μ΄λ»κ² λμλ λͺ¨λ λΉ μΉΈμ λ°μ΄λ¬μ€λ₯Ό νΌλ¨λ¦΄ μ μλ κ²½μ°μλ -1μ μΆλ ₯νλ€.
첫째 μ€μ μ°κ΅¬μμ ν¬κΈ° N(4 ≤ N ≤ 50), λμ μ μλ λ°μ΄λ¬μ€μ κ°μ M(1 ≤ M ≤ 10)
λμ§Έ μ€λΆν° Nκ°μ μ€μ μ°κ΅¬μμ μν
0μ λΉ μΉΈ, 1μ λ²½, 2λ λ°μ΄λ¬μ€ (Mλ³΄λ€ ν¬κ±°λ κ°κ³ , 10λ³΄λ€ μκ±°λ κ°μ μμ°μ)
from collections import deque
import copy
# μ°κ΅¬μμ ν¬κΈ° N, λμ μ μλ λ°μ΄λ¬μ€μ κ°μ
n, m = map(int, input().split())
graph = []
virus = []
# μ΅μ μκ°
min_time = int(1e9)
# λΆ λ λ¨ μ
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
for i in range(n):
data = list(map(int, input().split()))
graph.append(data)
for j in range(n):
if data[j] == 2:
# λΉνμ±ν λ°μ΄λ¬μ€
graph[i][j] == -1
# λ°μ΄λ¬μ€ μμΉ
virus.append((i, j))
def check(g):
for i in range(n):
for j in range(n):
# λΉ μΉΈμΈκ°
if g[i][j] == 0:
return False
return True
def combi(lst, num):
result = []
if num > len(lst):
return result
if num == 1:
for l in lst:
result.append([l])
elif num > 1:
for i in range(len(lst) - num + 1):
for t in combi(lst[i + 1:], num - 1):
result.append(t + [lst[i]])
return result
def bfs(g, combination):
global min_time
visited = [[False] * n for _ in range(n)]
queue = deque()
if check(g):
min_time = min(min_time, 0)
return
for c in combination:
a, b = c
visited[a][b] = True
# νμ± λ°μ΄λ¬μ€
g[a][b] = -2
# μμΉμ κ±Έλ¦° μκ°
queue.append((a, b, 0))
end_time = 0
while queue:
x, y, time = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny]:
# λ²½μ΄λ©΄
if g[nx][ny] == 1:
continue
else: # λΉμΉΈμ΄λ©΄
if g[nx][ny] == 0:
end_time = max(end_time, time + 1)
# νμ± λ°μ΄λ¬μ€
g[nx][ny] = -2
visited[nx][ny] = True
queue.append((nx, ny, time + 1))
if check(g):
min_time = min(min_time, end_time)
g = copy.deepcopy(graph)
for com in combi(virus, m):
g = copy.deepcopy(g)
bfs(g, com)
g = graph
if min_time == int(1e9):
print(-1)
else:
print(min_time)
μμ μ λ ₯
7 3
2 0 0 0 1 1 0
0 0 1 0 1 2 0
0 1 1 0 1 0 0
0 1 0 0 0 0 0
0 0 0 2 0 1 1
0 1 0 0 0 0 0
2 1 0 0 0 0 2
μμ μΆλ ₯
4

μ΄λ²μλ λ무 μ΄λ ΅λ€..........
μΈμ λνΌμ νλ €λ........
κ°μ¬ν©λλ€.
728x90
λ°μν