Untitled11.ipynb - Colab
Untitled11.ipynb - Colab
import itertools
import numpy as np
#Dynamic Programming
def tsp_dynamic_programming(distance_matrix):
n = len(distance_matrix)
memo = {}
min_cost = float("inf")
for next_city in range(n):
if visited & (1 << next_city) == 0: # If not yet visited
new_cost = distance_matrix[city][next_city] + visit(next_city, visited | (1 << next_city))
min_cost = min(min_cost, new_cost)
path.append(best_next[1])
last_city = best_next[1]
visited |= (1 << best_next[1])
return path
#Greedy Algorithm
def tsp_nearest_neighbor(distance_matrix):
n = len(distance_matrix)
start_city = 0
visited = [False] * n
visited[start_city] = True
path = [start_city]
total_cost = 0
current_city = start_city
for _ in range(n - 1):
nearest_city = None
min_distance = float("inf")
path.append(nearest_city)
total_cost += min_distance
visited[nearest_city] = True
current_city = nearest_city
# prompt: generate code to construct the graph for the above three algorithms comparing path cost and one more graph for path taken
# Assuming brute_force_path, brute_force_cost, dp_path, dp_cost, nn_path, nn_cost are defined from previous code
chevron_left 1 of 1
chevron_right thumb_up thumb_down Use code with caution
# prompt: the above graphs should be simple and at each point it should represent city name
import itertools
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(len(path))
y = [0] * len(path) # y-coordinates set to 0 for simple horizontal line representation
plt.plot(x, y, marker='o', linestyle='-') # Plot points
plt.xlabel("City Order")
plt.ylabel("City")
plt.title(f"Path Taken - {title}")
plt.yticks([]) # Remove y-axis ticks
plt.show()
# Example usage
visualize_path(brute_force_path, "Brute Force")
visualize_path(dp_path, "Dynamic Programming")
visualize_path(nn_path, "Nearest Neighbor")