๐ฃ๐ฟ๐ผ๐ด๐ฟ๐ฎ๐บ๐บ๐ถ๐ป๐ด๐ป/[๐๐ฒ๐ญ๐ก๐จ๐ง] ๐๐ฅ๐ ๐จ๐ซ๐ข๐ญ๐ก๐ฆ
[Python] ๋ฐฑ์ค 7576 & ๋ฐฑ์ค 14502
๐ค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. ๋๋ค์ผ๋ก ๋ฒฝ ์ธ์ธ๋๋ ์ฌ๊ท์์ ๋น ์ ธ๋์ฌ๋ ์์๋ณต๊ตฌ ํ๊ธฐ