https://www.acmicpc.net/problem/17142
์ผ์ฑ ์ฝํ ์์ itertools๋ฅผ ๋ชป์ด๋ค๋ ๋ง์ด ์์ด์ DFS์ BFS๋ฅผ ์ฌ์ฉํด ํ์ด๋ดค๋ค
from collections import deque
n, m = map(int, input().split())
room = []
for _ in range(n):
room.append(list(map(int, input().split())))
virus = []
for i in range(n):
for j in range(n):
if room[i][j] == 2:
virus.append([i, j])
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
# ๋ฐ์ด๋ฌ์ค๋ฅผ ํผ๋จ๋ฆฌ๋ ์ต์ ์๊ฐ ๊ตฌํ๊ธฐ
def bfs(active):
q = deque()
dist = [[-1] * n for _ in range(n)] # ๊ฐ ์นธ์ ๋ฐ์ด๋ฌ์ค๋ฅผ ํผ๋จ๋ฆฌ๋ ๋ฐ ๊ฑธ๋ฆฌ๋ ์๊ฐ
for y, x in active:
q.append([y, x])
dist[y][x] = 0
while q:
y, x = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < n and dist[ny][nx] == -1:
if room[ny][nx] == 0:
dist[ny][nx] = dist[y][x] + 1
q.append([ny, nx])
if room[ny][nx] == 2:
dist[ny][nx] = dist[y][x] + 1
q.append([ny, nx])
rst = 0
for i in range(n):
for j in range(n):
if room[i][j] == 0:
if dist[i][j] == -1:
rst = float('inf')
break
else:
rst = max(rst, dist[i][j])
if rst == float('inf'):
break
return rst
# ๋ฐ์ด๋ฌ์ค ์ค m๊ฐ ๊ณ ๋ฅด๊ธฐ
def dfs(idx, active):
global answer
if len(active) == m:
answer = min(answer, bfs(active))
if idx == len(virus):
return
dfs(idx+1, active+[virus[idx]])
dfs(idx+1, active)
answer = float('inf')
dfs(0, [])
if answer == float('inf'):
print(-1)
else:
print(answer)
์ด ๋ฌธ์ ์์ ์ด๋ ค์ ๋ ์ ์ ๋นํ์ฑ ๋ฐ์ด๋ฌ์ค๋ฅผ ์ฒ๋ฆฌํ๋ ๋ถ๋ถ์ด์๋๋ฐ
๋นํ์ฑ ๋ฐ์ด๋ฌ์ค๋ ํ์ฑ ๋ฐ์ด๋ฌ์ค๊ฐ ๋์ด ๋ฐ์ด๋ฌ์ค๋ฅผ ํผ๋จ๋ฆด ์ ์์ผ๋ฏ๋ก BFS ๋ด์์ ์ฒ๋ฆฌ๋ฅผ ํด์ค์ผ ํ๋ฉฐ, ๋ณต์ ๋๋๋ฐ 1์ด๊ฐ ๊ฑธ๋ฆฐ๋ค
โ
๋์ ๋ฌธ์ ์์ ์๊ตฌํ ๋ต์ '๋ชจ๋ ๋น ์นธ'์ ๋ฐ์ด๋ฌ์ค๋ฅผ ํผ๋จ๋ฆฌ๋ ์ต์ ์๊ฐ์ด๋ฏ๋ก ๋นํ์ฑ ๋ฐ์ด๋ฌ์ค๊ฐ ์๋ ๋ชจ๋ ์นธ์ ๋ฐ์ด๋ฌ์ค๋ฅผ ํผ๋จ๋ฆฌ์ง ์์๋ ๋๋ค
์ฆ, ๋ด ํ์ด์์ room์ด 0์ธ ๋ถ๋ถ์์์ dist ๋ฆฌ์คํธ ๊ฐ๋ง ๊ณ ๋ คํด์ฃผ๋ฉด ๋๋ค