1+ def link (arr , dir , x , y ):
2+ length = 0
3+ dx = [- 1 , 1 , 0 , 0 ]
4+ dy = [0 , 0 , - 1 , 1 ]
5+ while True :
6+ x += dx [dir ]
7+ y += dy [dir ]
8+
9+ # 전선이 전원까지 잘 연결되었으면 전선이 이어지는 부분을 표시하고 길이 반환
10+ if x < 0 or x >= N or y < 0 or y >= N :
11+ return length
12+
13+ # 전선이 중간에 다른 전선을 만났으면 이어지지 못하므로 길이 -1 반환
14+ if arr [x ][y ] != 0 :
15+ return - 1
16+
17+ arr [x ][y ] = 2
18+ length += 1
19+
20+
21+ def dfs (arr , coreNum , count , wire_length ):
22+ global ans , max_cores
23+
24+ if coreNum == len (core ):
25+ # 현재 연결된 코어 수가 더 많거나 코어 수가 같은데 전선 길이가 더 짧은 경우 답 갱신
26+ if count > max_cores or (count == max_cores and wire_length < ans ):
27+ max_cores = count
28+ ans = wire_length
29+ return
30+
31+ x , y = core [coreNum ]
32+ if x == 0 or x == N - 1 or y == 0 or y == N - 1 :
33+ # 가장자리에 있는 코어는 전선이 필요 없으므로 바로 다음 코어 탐색
34+ dfs (arr , coreNum + 1 , count + 1 , wire_length )
35+ return
36+
37+ for dir in range (4 ):
38+ arr_copy = [row [:] for row in arr ] # 백트래킹을 위해 복사
39+ length = link (arr_copy , dir , x , y )
40+ if length != - 1 :
41+ dfs (arr_copy , coreNum + 1 , count + 1 , wire_length + length )
42+
43+ # 현재 코어를 연결하지 않고 다음 코어 탐색
44+ dfs (arr , coreNum + 1 , count , wire_length )
45+
46+
47+ testCaseNum = int (input ())
48+ outputs = []
49+
50+ for test_case in range (1 , testCaseNum + 1 ):
51+ N = int (input ())
52+ arr = []
53+ core = []
54+ ans = float ('inf' )
55+ max_cores = 0
56+
57+ for i in range (N ):
58+ arr .append (list (map (int , input ().split ())))
59+ for j in range (N ):
60+ if arr [i ][j ] == 1 :
61+ core .append ((i , j ))
62+
63+ dfs (arr , 0 , 0 , 0 )
64+ outputs .append (f"#{ test_case } { ans } " )
65+
66+ for output in outputs :
67+ print (output )
0 commit comments