-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
79931dd
commit 44da9e5
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import numpy as np | ||
|
||
def nearest_neighbor_tsp(cities): | ||
num_cities = len(cities) | ||
if num_cities < 2: | ||
return cities | ||
|
||
# Initialize variables | ||
unvisited_cities = set(range(num_cities)) | ||
tour = [0] # Start with the first city as the initial city | ||
current_city = 0 | ||
|
||
while unvisited_cities: | ||
nearest_city = min(unvisited_cities, key=lambda city: np.linalg.norm(cities[current_city] - cities[city])) | ||
tour.append(nearest_city) | ||
current_city = nearest_city | ||
unvisited_cities.remove(nearest_city) | ||
|
||
# Return to the starting city to complete the tour | ||
tour.append(tour[0]) | ||
|
||
return [cities[i] for i in tour] | ||
|
||
# Example usage: | ||
cities = np.array([[0, 0], [2, 4], [3, 1], [5, 3], [6, 5]]) | ||
optimal_tour = nearest_neighbor_tsp(cities) |