File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import sys
2+
3+ sys .stdin = open ('bj_10971_in.txt' , 'r' )
4+ input = sys .stdin .readline
5+
6+ '''
7+ 1. 시작점에 따라 비용이 달라질수 있으므로 시작점을 각 도시마다 한번씩 지정해서 해야함.
8+ '''
9+
10+ n = int (input ().strip ())
11+ costs = [list (map (int , input ().strip ().split ())) for _ in range (n )] #도시: 0 ~ (n-1)
12+ visited = [False ]* n
13+ # print(visited)
14+ # print(costs)
15+
16+
17+ def dfs (start , cnt , cost ):
18+ global ans
19+
20+ # 가지치기: 현재 비용이 이미 최솟값보다 크면 중단
21+ if cost >= ans :
22+ return
23+
24+ #종료조건
25+ if cnt == n : #마지막 도시면
26+ if costs [start ][0 ] == 0 : #처음 도시로 못 돌아간다면
27+ return
28+
29+ #처음 도시로 가는 비용 계산
30+ ans = min (ans , cost + costs [start ][0 ])
31+ # print(ans)
32+ return
33+
34+ for end in range (n ): #도시: 0 ~ (n-1) = n개
35+ if costs [start ][end ] == 0 or visited [end ]: #비용이 0이거나 도시를 방문 했으면
36+ continue
37+
38+ visited [end ] = True
39+ dfs (end , cnt + 1 , cost + costs [start ][end ])
40+ visited [end ] = False
41+
42+ ans = sys .maxsize
43+
44+
45+ visited [0 ] = True
46+ dfs (0 , 1 , 0 )
47+
48+ print (ans )
Original file line number Diff line number Diff line change 1+ 4
2+ 0 10 15 20
3+ 5 0 9 10
4+ 6 13 0 12
5+ 8 8 9 0
You can’t perform that action at this time.
0 commit comments