[Gold I] Gaaaaaaaaaarden - 18809

문제 링크

성능 요약

메모리: 146996 KB, 시간: 3292 ms

분류

너비 우선 탐색, 브루트포스 알고리즘, 그래프 이론, 그래프 탐색, 구현, 시뮬레이션

제출 일자

2023년 11월 23일 17:53:29

문제 설명

길고 길었던 겨울이 끝나고 BOJ 마을에도 봄이 찾아왔다. BOJ 마을에서는 꽃을 마을 소유의 정원에 피우려고 한다. 정원은 땅과 호수로 이루어져 있고 2차원 격자판 모양이다.

인건비 절감을 위해 BOJ 마을에서는 직접 사람이 씨앗을 심는 대신 초록색 배양액과 빨간색 배양액을 땅에 적절하게 뿌려서 꽃을 피울 것이다. 이 때 배양액을 뿌릴 수 있는 땅은 미리 정해져있다.

배양액은 매 초마다 이전에 배양액이 도달한 적이 없는 인접한 땅으로 퍼져간다.

아래는 초록색 배양액 2개를 뿌렸을 때의 예시이다. 하얀색 칸은 배양액을 뿌릴 수 없는 땅을, 황토색 칸은 배양액을 뿌릴 수 있는 땅을, 하늘색 칸은 호수를 의미한다.

초록색 배양액과 빨간색 배양액이 동일한 시간에 도달한 땅에서는 두 배양액이 합쳐져서 꽃이 피어난다. 꽃이 피어난 땅에서는 배양액이 사라지기 때문에 더 이상 인접한 땅으로 배양액을 퍼트리지 않는다.

아래는 초록색 배양액 2개와 빨간색 배양액 2개를 뿌렸을 때의 예시이다.

배양액은 봄이 지나면 사용할 수 없게 되므로 주어진 모든 배양액을 남김없이 사용해야 한다. 예를 들어 초록색 배양액 2개와 빨간색 배양액 2개가 주어졌는데 초록색 배양액 1개를 땅에 뿌리지 않고, 초록색 배양액 1개와 빨간색 배양액 2개만을 사용하는 것은 불가능하다.

또한 모든 배양액은 서로 다른 곳에 뿌려져야 한다.

정원과 두 배양액의 개수가 주어져있을 때 피울 수 있는 꽃의 최대 개수를 구해보자.

입력

첫째 줄에 정원의 행의 개수와 열의 개수를 나타내는 N(2 ≤ N ≤ 50)과 M(2 ≤ M ≤ 50), 그리고 초록색 배양액의 개수 G(1 ≤ G ≤ 5)와 빨간색 배양액의 개수 R(1 ≤ R ≤ 5)이 한 칸의 빈칸을 사이에 두고 주어진다.

그 다음 N개의 줄에는 각 줄마다 정원의 각 행을 나타내는 M개의 정수가 한 개의 빈 칸을 사이에 두고 주어진다. 각 칸에 들어가는 값은 0, 1, 2이다. 0은 호수, 1은 배양액을 뿌릴 수 없는 땅, 2는 배양액을 뿌릴 수 있는 땅을 의미한다.

배양액을 뿌릴 수 있는 땅의 수는 R+G개 이상이고 10개 이하이다.

출력

첫째 줄에 피울 수 있는 꽃의 최대 개수를 출력한다.

💡 Solutions

📄 Gaaaaaaaaaarden.py

import sys
from collections import deque
from itertools import combinations

# N = int(sys.stdin.readline())


def selectLand(position, Green_Red, now, sp):
    global answer
    if now == G + R:
        answer = max(answer, simulation(position, sp))
        return 
    
    if Green_Red[0] :
        Green_Red[0] -= 1
        seletedColor[now] = True
        selectLand(position, Green_Red, now + 1, sp)
        Green_Red[0] += 1

    if Green_Red[1] :
        Green_Red[1] -= 1
        seletedColor[now] = False
        selectLand(position, Green_Red, now + 1, sp)
        Green_Red[1] += 1

    
def simulation(position, start_point):
    
    for i in range(R+G):
        # G는 3번 R은 4번으로 배양액 뿌리기
        matrix[pos[i][0]][pos[i][1]] = 3 if position[i] else 4
    
    result = bfs(matrix, start_point)

    for i in range(R+G):
        # G는 3번 R은 4번으로 배양액 뿌리기
        matrix[pos[i][0]][pos[i][1]] = 2

    return result


def bfs(ground, start_point):
    result = 0
    is_visited = [[0 for _ in range(M)] for _ in range(N)]
    que = deque(start_point)

    for x, y in start_point:
        is_visited[x][y] = matrix[x][y]

    next_current = []

    while que or next_current:
        
        # 날이 지날경우 꽃이 핀지 안핀지 확인
        if not que:

            finishGround = set()
            nxt_curt = set()
            for gx, gy, color in next_current:
                
                if is_visited[gx][gy] == 0 and (ground[gx][gy] == 1 or ground[gx][gy] == 2):
                    is_visited[gx][gy] = color
                    nxt_curt.add((gx, gy))
                elif color != is_visited[gx][gy] :
                    is_visited[gx][gy] = 7
                    finishGround.add((gx, gy))
                

            que = deque(list(nxt_curt - finishGround))

            result += len(finishGround)
            next_current = []
            continue
        
        x, y = que.pop()

        for dx, dy in ((0,1), (0,-1), (1,0), (-1,0)):
            nx = x + dx
            ny = y + dy

            if nx < 0 or ny < 0 or nx >= N or ny >= M : continue
            if is_visited[nx][ny] or ground[nx][ny] == 0: continue
            if ground[nx][ny] != 1 and ground[nx][ny] != 2 : continue

            
            next_current.append([nx, ny, is_visited[x][y]])

    return result

# seg_tree = [0]*(4*N)
N, M, G, R = list(map(int,sys.stdin.readline().split()))
matrix = [list(map(int,sys.stdin.readline().split())) for _ in range(N)]
answer = 0

ok_land = []
for n in range(N):
    for m in range(M):
        if matrix[n][m] == 2: ok_land.append((n,m))

# 배양액 G 배양 R 배양액 나둘 위치 결정해야함
# G는 True R는 False 로 작업해서 색 구분
 
seletedColor = [False for _ in range(G+R)]
for pos in combinations(ok_land, G+R):
    selectLand(seletedColor, [G, R], 0, pos)

print(answer)
질문/피드백

이 문제 풀이가 궁금하면 GitHub Issues에 남겨주세요. 확인되는 대로 답변드릴게요.

이 문제로 질문하기 →