[๋ฐฑ์ค€ ๐Ÿฅ‡3] 17142๋ฒˆ ์—ฐ๊ตฌ์†Œ 3 (Python/ํŒŒ์ด์ฌ)

mingssoยท2023๋…„ 3์›” 19์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
18/35

1๏ธโƒฃ ๋ฌธ์ œ

https://www.acmicpc.net/problem/17142



2๏ธโƒฃ ์ฝ”๋“œ

์‚ผ์„ฑ ์ฝ”ํ…Œ์—์„œ 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)



3๏ธโƒฃ ํ’€์ด

์ด ๋ฌธ์ œ์—์„œ ์–ด๋ ค์› ๋˜ ์ ์€ ๋น„ํ™œ์„ฑ ๋ฐ”์ด๋Ÿฌ์Šค๋ฅผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ถ€๋ถ„์ด์—ˆ๋Š”๋ฐ
๋น„ํ™œ์„ฑ ๋ฐ”์ด๋Ÿฌ์Šค๋„ ํ™œ์„ฑ ๋ฐ”์ด๋Ÿฌ์Šค๊ฐ€ ๋˜์–ด ๋ฐ”์ด๋Ÿฌ์Šค๋ฅผ ํผ๋œจ๋ฆด ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ BFS ๋‚ด์—์„œ ์ฒ˜๋ฆฌ๋ฅผ ํ•ด์ค˜์•ผ ํ•˜๋ฉฐ, ๋ณต์ œ๋˜๋Š”๋ฐ 1์ดˆ๊ฐ€ ๊ฑธ๋ฆฐ๋‹ค
โ€‹
๋Œ€์‹  ๋ฌธ์ œ์—์„œ ์š”๊ตฌํ•œ ๋‹ต์€ '๋ชจ๋“  ๋นˆ ์นธ'์— ๋ฐ”์ด๋Ÿฌ์Šค๋ฅผ ํผ๋œจ๋ฆฌ๋Š” ์ตœ์†Œ ์‹œ๊ฐ„์ด๋ฏ€๋กœ ๋น„ํ™œ์„ฑ ๋ฐ”์ด๋Ÿฌ์Šค๊ฐ€ ์žˆ๋Š” ๋ชจ๋“  ์นธ์— ๋ฐ”์ด๋Ÿฌ์Šค๋ฅผ ํผ๋œจ๋ฆฌ์ง€ ์•Š์•„๋„ ๋œ๋‹ค
์ฆ‰, ๋‚ด ํ’€์ด์—์„œ room์ด 0์ธ ๋ถ€๋ถ„์—์„œ์˜ dist ๋ฆฌ์ŠคํŠธ ๊ฐ’๋งŒ ๊ณ ๋ คํ•ด์ฃผ๋ฉด ๋œ๋‹ค

profile
๐Ÿฅ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ’ฐ

0๊ฐœ์˜ ๋Œ“๊ธ€