https://www.codetree.ai/missions/2/problems/traveling-salesman-problem/description
코드트리 | 코딩테스트 준비를 위한 알고리즘 정석
국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.
www.codetree.ai
n = int(input())
graph = []
for _ in range(n):
temp = list(map(int, input().rstrip().split(" ")))
graph.append(temp)
num = [i for i in range(1, n)]
visited = [0 for _ in range(n-1)]
cnt = 100000
answer = []
def find_cost(temp):
answer = []
cnt = 0
for i in range(len(temp)-1):
answer.append([temp[i], temp[i+1]])
for i, j in answer:
if graph[i][j] == 0:
return 0
cnt += graph[i][j]
return cnt
def backtrack(dep):
global cnt
if dep == n-1:
temp = [0] + answer[::] + [0]
if find_cost(temp) != 0:
cnt = min(find_cost(temp), cnt)
return
for i in range(n-1):
if not visited[i]:
answer.append(num[i])
visited[i] = 1
backtrack(dep+1)
answer.pop()
visited[i] = 0
backtrack(0)
print(cnt)
728x90
반응형
'🔻PS > Codetree' 카테고리의 다른 글
[Codetree] 정수 n개의 합 2 Python (0) | 2024.09.19 |
---|---|
[Codetree] 수들 중 최솟값 최대화하기 Python (0) | 2024.09.12 |
[Codetree] 수들의 합 최대화하기 Python (0) | 2024.09.12 |
[Codetree] 1차원 윷놀이 Python (3) | 2024.09.08 |
[Codetree] 강력한 폭발 Python (0) | 2024.09.05 |