[알고리즘] 백준 14502 연구소

CHOI IN HO·2024년 2월 26일
0

코딩테스트

목록 보기
56/74

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


풀이

벽을 임의로 3개 세우는 함수에는 dfs를 전이 시키는 함수에는 bfs를 사용해서 풀었다.
이때 참고할 점은 dfs부분에서 넣어준 함수가 bfs 실행 이후에도 같아야 하기 때문에 temp_array라는 새로운 배열을 만들어서 넣어주었다.

temp_array = [row[:] for row in graph]

from collections import deque
import sys

virus = []

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

n, m = map(int, sys.stdin.readline().split())
array = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]

for i in range(n):
    for j in range(m):
        if array[i][j] == 2:
            virus.append((i,j))

mx = 0

def bfs(lst):
    q = deque(virus)
    while q:
        x, y = q.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < n and 0 <= ny < m:
                if lst[nx][ny] == 0:
                    lst[nx][ny] = 2
                    q.append((nx, ny))

    count = 0
    for i in range(n):
        for j in range(m):
            if lst[i][j] == 0:
                count += 1
    return count

def dfs(count, graph):
    global mx
    if count == 3:
        temp_array = [row[:] for row in graph]  # Deep copy of the graph
        mx = max(mx, bfs(temp_array))
        return
    for i in range(n):
        for j in range(m):
            if graph[i][j] == 0:
                graph[i][j] = 1
                dfs(count + 1, graph)
                graph[i][j] = 0

dfs(0, array)
print(mx)
profile
개발자기 되기 위해선 무엇이든!

0개의 댓글