[5, 0, 4, 6], [3, 4, 0, 9], [8, 6, 9, 0]] total_cost = 0 current_city = 0 visited = [True, False, False, False] order = [0] # 都市0以外のN-1都市を訪問するまでループ for _ in range(N - 1): # 最も近い次の都市を全探索 best_cost = 1000000000 best_city = -1 for next_city in range(N): if visited[next_city]: continue # コストが最小の場合は更新 next_cost = total_cost + cost[current_city][next_city] if next_cost < best_cost: best_cost = next_cost best_city = next_city # 次の都市に移動し、状態を更新する visited[best_city] = True order.append(best_city) total_cost = best_cost current_city = best_city # 最後に都市0に戻ってくる total_cost += cost[current_city][0] order.append(0) print(f"total_cost: {total_cost}") print(f"order: {order}") 入力の作成 合計コスト・現在位置・訪問済みフラグ・訪問順を初期化 都市0以外を全て訪問するまでループ まだ訪問していない都市を全探索し、 最もコストが小さい都市を次の都市として選ぶ 次の都市に移動する 合計コスト・現在位置・訪問済みフラグ・訪問順を更新 最後に都市0に戻る 合計コスト・訪問順を出力して終了