Skip to content

Commit d5597f5

Browse files
authored
[BOJ] 14502 연구소 (G4)
1 parent 82edf84 commit d5597f5

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

박예진/0주차/BFS/14502.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import sys
2+
input = sys.stdin.readline
3+
from collections import deque
4+
5+
N, M = map(int, input().split())
6+
arr = [list(map(int, input().split())) for _ in range(N)]
7+
zeros = []
8+
dx = [-1, 0, 1, 0]
9+
dy = [0, 1, 0, -1]
10+
answer = 0
11+
12+
def OOB(x, y):
13+
return x < 0 or x >= N or y < 0 or y >= M
14+
15+
# 바이러스 퍼트리기
16+
def bfs(temp):
17+
q = deque()
18+
19+
for i in range(N):
20+
for j in range(M):
21+
if temp[i][j] == 2:
22+
q.append((i, j))
23+
24+
while q:
25+
x, y = q.popleft()
26+
27+
for dir in range(4):
28+
nx = x + dx[dir]
29+
ny = y + dy[dir]
30+
31+
if OOB(nx, ny):
32+
continue
33+
if temp[nx][ny] == 0:
34+
q.append((nx, ny))
35+
temp[nx][ny] = 2
36+
37+
# 0인 곳들 중 3개 백트래킹 후, BFS
38+
wall_idx = []
39+
def dfs(depth, start):
40+
global answer
41+
42+
if depth == 3:
43+
# 깊은 복사
44+
temp = [row[:] for row in arr]
45+
# 벽 세우기
46+
for idx in wall_idx:
47+
x, y = zeros[idx]
48+
temp[x][y] = 1
49+
# 바이러스 퍼트리기
50+
bfs(temp)
51+
# temp 중 남은 안전지역
52+
cnt = 0
53+
for i in range(N):
54+
for j in range(M):
55+
if temp[i][j] == 0:
56+
cnt += 1
57+
58+
answer = max(answer, cnt)
59+
return
60+
61+
for i in range(start, len(zeros)):
62+
wall_idx.append(i)
63+
dfs(depth + 1, i + 1)
64+
wall_idx.pop()
65+
66+
# 0인 곳 위치 파악
67+
for i in range(N):
68+
for j in range(M):
69+
if arr[i][j] == 0:
70+
zeros.append((i, j))
71+
72+
dfs(0, 0)
73+
print(answer)

0 commit comments

Comments
 (0)