๐Ÿ—๏ธ Algorithm/๐ŸŸฉ ๋ฐฑ์ค€

๐ŸŸฉ [๋ฐฑ์ค€] [Python] [BFS/DFS] 14502๋ฒˆ_์—ฐ๊ตฌ์†Œ

Dbswnstjd 2022. 11. 16. 10:06

๋ฌธ์ œ

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

 

14502๋ฒˆ: ์—ฐ๊ตฌ์†Œ

์ธ์ฒด์— ์น˜๋ช…์ ์ธ ๋ฐ”์ด๋Ÿฌ์Šค๋ฅผ ์—ฐ๊ตฌํ•˜๋˜ ์—ฐ๊ตฌ์†Œ์—์„œ ๋ฐ”์ด๋Ÿฌ์Šค๊ฐ€ ์œ ์ถœ๋˜์—ˆ๋‹ค. ๋‹คํ–‰ํžˆ ๋ฐ”์ด๋Ÿฌ์Šค๋Š” ์•„์ง ํผ์ง€์ง€ ์•Š์•˜๊ณ , ๋ฐ”์ด๋Ÿฌ์Šค์˜ ํ™•์‚ฐ์„ ๋ง‰๊ธฐ ์œ„ํ•ด์„œ ์—ฐ๊ตฌ์†Œ์— ๋ฒฝ์„ ์„ธ์šฐ๋ ค๊ณ  ํ•œ๋‹ค. ์—ฐ๊ตฌ์†Œ๋Š” ํฌ

www.acmicpc.net

ํ’€์ด

# ๋ฐฑ์ค€ 14502๋ฒˆ ๋ฌธ์ œ - ์—ฐ๊ตฌ์†Œ
from collections import deque
import copy
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
graph = []
dx, dy = [0,0,-1,1], [1,-1,0,0]
for _ in range(n):
    graph.append(list(map(int, input().split())))
def bfs():
    queue = deque()
    temp_graph = copy.deepcopy(graph)
    for i in range(n):
        for j in range(m):
            if temp_graph[i][j] == 2:
                queue.append((i,j))
    while queue:
        x, y = queue.popleft()
    
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= n or ny < 0 or ny >= m:
                continue
            if temp_graph[nx][ny] == 0:
                temp_graph[nx][ny] = 2
                queue.append((nx,ny))
    cnt = 0
    global answer
    for i in range(n):
        cnt += temp_graph[i].count(0)

    answer = max(answer, cnt)

def makeWall(cnt,x,y):
    if cnt == 3:
        bfs()
        return
    # ์‹œ๊ฐ„์ดˆ๊ณผ๋ฅผ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด 
    # ์ด์ „ ์žฌ๊ท€์—์„œ ํƒ์ƒ‰ํ•œ ๋ฒ”์œ„๋ฅผ ์ œ์™ธํ•˜๊ณ  for๋ฌธ ์ˆ˜ํ–‰
    for i in range(x, n):
        if i == x:
            k = y
        else:
            k = 0
        for j in range(k, m):
            if graph[i][j] == 0:
                graph[i][j] = 1
                makeWall(cnt+1,i,j)
                graph[i][j] = 0
answer = 0 
makeWall(0,0,0)
print(answer)