0% found this document useful (0 votes)
13 views2 pages

Nearest Neighbor TSP Algorithm

The document contains a Python function that implements the nearest neighbor algorithm for solving the Traveling Salesman Problem (TSP). It calculates the shortest route visiting all cities based on a distance matrix and returns the route along with the total distance. An example is provided, demonstrating the function with a sample distance matrix, resulting in a tour and total distance output.

Uploaded by

mallika7795400
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views2 pages

Nearest Neighbor TSP Algorithm

The document contains a Python function that implements the nearest neighbor algorithm for solving the Traveling Salesman Problem (TSP). It calculates the shortest route visiting all cities based on a distance matrix and returns the route along with the total distance. An example is provided, demonstrating the function with a sample distance matrix, resulting in a tour and total distance output.

Uploaded by

mallika7795400
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

6B.

neighbor

def nearest_neighbor_tsp(distances):

n = len(distances)

visited = [False] * n #initial

route = []

total_distances = 0.0

#start city

current_city = 0

[Link](current_city)

visited[current_city] = True

for _ in range(1,n):

nearest_city = -1

min_dist = float('inf')

for i in range(n):

if not visited[i] and distances[current_city][i] < min_dist:

min_dist = distances[current_city][i]

nearest_city = i

if nearest_city != -1:

[Link](nearest_city)

visited[nearest_city] = True

total_distances += min_dist

current_city = nearest_city

else:

break

total_distances += distances[current_city][route[0]]

[Link](route[0])
return route, total_distances

if __name__ == "__main__":

distances = [

[0, 10, 15, 20],

[10, 0, 35, 25],

[15, 35, 0, 30],

[20, 25, 30, 0]

tour, dist = nearest_neighbor_tsp(distances)

print(f"Tour: {tour}")

print(f"Total Distances:{dist}")

output

Tour: [0, 1, 3, 2, 0]
Total Distances:80.0
In [ ]:

You might also like