Skip to content

Commit 20efbcb

Browse files
committed
BOJ UPDATE
1 parent 4a14d2a commit 20efbcb

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

12_Backtracking/bj_10971.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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)

12_Backtracking/bj_10971_in.txt

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
4
2+
0 10 15 20
3+
5 0 9 10
4+
6 13 0 12
5+
8 8 9 0

0 commit comments

Comments
 (0)