1+ import sys ; input = sys .stdin .readline
2+ import copy
3+
4+ # CCTV 종류별, 바라보는 방향별 감시영역 재귀적 탐색
5+ def dfs (graph , depth ):
6+ global answer
7+ # 종료 조건: 모든 CCTV 탐색
8+ if depth == len (cctv_list ):
9+ # 사각지대 최솟값
10+ answer = min (answer , count_zero (graph ))
11+ return
12+ else :
13+ # 사무실 정보 깊은 복사
14+ graph_copy = copy .deepcopy (graph )
15+ x , y , cctv_type = cctv_list [depth ]
16+ for cctv_dir in cctv_direction [cctv_type ]:
17+ # CCTV 감시영역 구하는 함수 호출
18+ watch (x , y , cctv_dir , graph_copy )
19+ # 현재 Case에서 타 모든 CCTV 재귀적 탐색
20+ dfs (graph_copy , depth + 1 )
21+ # CCTV를 다른 방향으로 회전시킨 후 재탐색하기 위함
22+ graph_copy = copy .deepcopy (graph )
23+
24+ # CCTV 감시영역 구하는 함수
25+ def watch (x , y , direction , graph ):
26+ for d in direction :
27+ nx , ny = x , y
28+ # 특정 방향으로 벽을 만나거나 사무실을 벗어나기 전까지 탐색
29+ while True :
30+ nx += direction_list [d ][0 ]
31+ ny += direction_list [d ][1 ]
32+ # 맵 내 위치
33+ if 0 <= nx < N and 0 <= ny < M :
34+ # 벽을 만난 경우
35+ if graph [nx ][ny ] == 6 :
36+ break
37+ # 새로운 감시가능 영역일 경우
38+ elif graph [nx ][ny ] == 0 :
39+ graph [nx ][ny ] = '#'
40+ # 맵 외 위치
41+ else :
42+ break
43+
44+ # 사각지대 개수 구하는 함수
45+ def count_zero (graph ):
46+ cnt = 0
47+ for i in range (N ):
48+ for j in range (M ):
49+ if graph [i ][j ] == 0 :
50+ cnt += 1
51+ return cnt
52+
53+ if __name__ == '__main__' :
54+ N , M = map (int , input ().split ())
55+ graph = [list (map (int , input ().split ())) for _ in range (N )]
56+ # 최솟값을 구하기 위해 초기값 10억 세팅
57+ answer = int (1e9 )
58+ cctv_list = []
59+ for i in range (N ):
60+ for j in range (M ):
61+ if 1 <= graph [i ][j ] <= 5 :
62+ # CCTV 좌표 및 종류 저장
63+ cctv_list .append ((i , j , graph [i ][j ]))
64+ # 탐색 방향: 상, 하, 좌, 우
65+ direction_list = [(- 1 , 0 ), (1 , 0 ), (0 , - 1 ), (0 , 1 )]
66+ # CCTV별 이동 가능한 방향
67+ cctv_direction = [
68+ [],
69+ [[0 ], [1 ], [2 ], [3 ]], # 1번 CCTV
70+ [[0 , 1 ], [2 , 3 ]], # 2번 CCTV
71+ [[0 , 2 ], [0 , 3 ], [1 , 2 ], [1 , 3 ]], # 3번 CCTV
72+ [[0 , 1 , 2 ], [0 , 1 , 3 ], [0 , 2 , 3 ], [1 , 2 , 3 ]], # 4번 CCTV
73+ [[0 , 1 , 2 , 3 ]] # 5번 CCTV
74+ ]
75+ dfs (graph , 0 )
76+ print (answer )
0 commit comments