1+ import copy
2+ import sys
3+ from collections import deque
4+ from itertools import combinations
5+ input = sys .stdin .readline
6+
7+ # 바이러스가 연구소 내에 확산되는 것을 시뮬레이션 하는 함수
8+ def bfs (new_lab , viruses ):
9+ N = len (new_lab )
10+ M = len (new_lab [0 ])
11+ queue = deque (viruses )
12+ visited = [[False for _ in range (M )] for _ in range (N )]
13+
14+ while queue :
15+ x , y = queue .popleft ()
16+ for dx , dy in ((- 1 , 0 ), (1 , 0 ), (0 , - 1 ), (0 , 1 )): # 인접한 네 방향 확인
17+ nx , ny = x + dx , y + dy
18+ # 범위 내에 있고, 아직 확산되지 않은 곳이라면
19+ if (0 <= nx < N and 0 <= ny < M ) and new_lab [nx ][ny ] == 0 and not visited [nx ][ny ]:
20+ new_lab [nx ][ny ] = 2 # 바이러스 확산
21+ visited [nx ][ny ] = True # 방문 표시
22+ queue .append ((nx , ny )) # 큐에 추가
23+
24+ def get_safe_area (new_lab ):
25+ cnt = 0
26+ for row in new_lab :
27+ cnt += row .count (0 )
28+ return cnt
29+ #return sum(row.count(0) for row in new_lab)
30+
31+ def solve (N , M , lab ):
32+ empty_spaces = [] # 빈 칸의 위치를 담을 리스트
33+ viruses = [] # 바이러스의 위치를 담을 리스트
34+ # 빈 공간과 바이러스의 위치 저장
35+ for i in range (N ):
36+ for j in range (M ):
37+ if lab [i ][j ] == 0 : # 빈 칸
38+ empty_spaces .append ((i , j ))
39+ if lab [i ][j ] == 2 : # 바이러스
40+ viruses .append ((i , j ))
41+
42+ max_safe_area = 0 # 최대 안전 영역 크기를 저장할 변수
43+
44+ for walls in combinations (empty_spaces , 3 ):
45+ new_lab = copy .deepcopy (lab ) # 깊은 복사를 사용하여 lab 복사
46+
47+ # 벽 설치
48+ for x , y in walls :
49+ new_lab [x ][y ] = 1
50+
51+ # 바이러스 확산시킴
52+ bfs (new_lab , viruses )
53+
54+ # 영역 크기 계산
55+ safe_area_cnt = get_safe_area (new_lab )
56+ # 현재 조합의 safe_area가 max_safe_area보다 크다면 값 업데이트
57+ max_safe_area = max (max_safe_area , safe_area_cnt )
58+
59+ return max_safe_area
60+
61+
62+ # 입출력
63+ N , M = map (int , input ().split ())
64+ lab = [list (map (int , input ().split ())) for _ in range (N )]
65+
66+ print (solve (N , M , lab ))
0 commit comments