๐ŸคRyusun๐Ÿค 2023. 6. 2. 20:50
# ๋ฐฑ์ค€ 7576

from collections import deque
import sys

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

d_row = [0, -1, 0, +1]
d_col = [+1, 0, -1, 0]
# ์ •์ˆ˜ 1์€ ์ต์€ ํ† ๋งˆํ† , ์ •์ˆ˜ 0์€ ์ต์ง€ ์•Š์€ ํ† ๋งˆํ† , ์ •์ˆ˜ -1์€ ํ† ๋งˆํ† ๊ฐ€ ๋“ค์–ด์žˆ์ง€ ์•Š์€ ์นธ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.
def bfs():
    queue = deque()
    count = 0
    for i in range(n):
        for j in range(m):
            if graph[i][j] == 1:
                queue.append([i,j])
    while queue:
        x,y = queue.popleft()
        for i in range(4):
            # ์ต์€ ํ† ๋งˆํ†  ์ƒํ•˜์ขŒ์šฐ ๋Œ๋ฉด์„œ ์ผ์ˆ˜ ์ €์žฅ
            nx = x + d_row[i]
            ny = y + d_col[i]
            if nx< 0 or ny < 0 or nx > n-1 or ny > m-1:
                continue
            if graph[nx][ny] == 0:
                graph[nx][ny] = graph[x][y] + 1
                queue.append([nx,ny])

bfs()
answer = 0

for i in range(M):
    for j in range(N):
        if graph[i][j] == 0:
            print(-1)
            exit()
        answer = max(answer, graph[i][j])
print(answer-1)

 

# ๋ฐฑ์ค€ 14502๋ฒˆ

from collections import deque
import copy

n, m = map(int, input().split(' '))
graph = []
for _ in range(n):
    graph.append(list(map(int, sys.stdin.readline().split())))

d_row = [0, -1, 0, +1]
d_col = [+1, 0, -1, 0]

def make_wall(cnt):
    if cnt == 3:
        bfs()
        return
    for i in range(n):
        for j in range(m):
            if graph[i][j] == 0:
                graph[i][j] = 1
                make_wall(cnt+1)
                graph[i][j] = 0

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 z in range(4):
            nx = x + d_row[z]
            ny = y + d_col[z]
            if nx < 0 or ny < 0 or nx > n - 1 or ny > m - 1:
               continue
            if temp_graph[nx][ny] == 0:
               temp_graph[nx][ny] = 2
               queue.append((nx, ny))

    global result
    cnt = 0
    for w in range(n):
        cnt += temp_graph[w].count(0)

    result = max(result,cnt)

result = 0
make_wall(0)
print(result)

 

 

๐Ÿ“ Points

1. ์ตœ์†Œ, ์ตœ๋Œ€ ์ผ์ˆ˜ ๊ตฌํ• ๋•Œ๋Š” graph ์— ๊ฐ’ ์ €์žฅ

2. ๋žœ๋ค์œผ๋กœ ๋ฒฝ ์„ธ์šธ๋•Œ๋Š” ์žฌ๊ท€์—์„œ ๋น ์ ธ๋‚˜์˜ฌ๋•Œ ์›์ƒ๋ณต๊ตฌ ํ•˜๊ธฐ