1+ import sys
2+ import copy
3+
4+ input = sys .stdin .readline
5+
6+ N , M = map (int , input ().split ())
7+ office = [list (map (int , input ().split ())) for _ in range (N )]
8+
9+ # CCTV 위치 저장
10+ cctvs = []
11+ for i in range (N ):
12+ for j in range (M ):
13+ if 1 <= office [i ][j ] <= 5 :
14+ cctvs .append ((i , j , office [i ][j ]))
15+
16+ total_cctv = len (cctvs ) # 전체 CCTV 개수
17+ min_blind_spot = 1e9 # 정답으로 반환할 사각지대 개수
18+
19+ # CCTV별 방향 설정
20+ directions = [(- 1 , 0 ), (0 , 1 ), (1 , 0 ), (0 , - 1 )] # 상 -> 우 -> 하 -> 좌
21+ cctv_dirs = {
22+ 1 : [[0 ], [1 ], [2 ], [3 ]],
23+ 2 : [[0 , 2 ], [1 , 3 ]],
24+ 3 : [[0 , 1 ], [1 , 2 ], [2 , 3 ], [3 , 0 ]],
25+ 4 : [[0 , 1 , 2 ], [1 , 2 , 3 ], [2 , 3 , 0 ], [3 , 0 , 1 ]],
26+ 5 : [[0 , 1 , 2 , 3 ]]
27+ }
28+
29+
30+ # 사각지대 개수 구하는 함수
31+ def count_zero (temp ):
32+ cnt = 0
33+ for i in range (N ):
34+ for j in range (M ):
35+ if temp [i ][j ] == 0 :
36+ cnt += 1
37+ return cnt
38+
39+
40+ # DFS 함수
41+ def dfs (idx , office ):
42+ global min_blind_spot
43+ # 종료 조건
44+ if idx == total_cctv :
45+ # 종료할 때는 사각지대(= 0) 개수 세고, 최소값 갱신해야 한다.
46+ blind_spot = count_zero (office )
47+ min_blind_spot = min (min_blind_spot , blind_spot )
48+ return
49+
50+ x , y , number = cctvs [idx ]
51+ for cctv_dir in cctv_dirs [number ]:
52+ # temp에 현재 office 리스트 깊은 복사
53+ temp = copy .deepcopy (office )
54+
55+ for dir in cctv_dir :
56+ dx , dy = directions [dir ]
57+ nx , ny = x + dx , y + dy
58+
59+ while 0 <= nx < N and 0 <= ny < M and temp [nx ][ny ] != 6 :
60+ if temp [nx ][ny ] == 0 :
61+ temp [nx ][ny ] = '#' # CCTV 감시OK
62+ nx += dx
63+ ny += dy
64+
65+ dfs (idx + 1 , temp )
66+
67+
68+ dfs (0 , office )
69+ print (min_blind_spot )
0 commit comments