50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
import math
|
|
import random
|
|
from model.base_model import Model
|
|
|
|
class MyBFSModel(Model):
|
|
def __init__(self):
|
|
super().__init__()
|
|
|
|
def init(self, nodes):
|
|
"""
|
|
Put your initialization here.
|
|
"""
|
|
super().init(nodes)
|
|
|
|
def fit(self, max_it=1000):
|
|
"""
|
|
Put your iteration process here.
|
|
"""
|
|
|
|
UCS_solutions = []
|
|
|
|
for i in range(0, self.N):
|
|
solution = [i]
|
|
UCS_solutions.append(solution)
|
|
|
|
# Breadth First: Set each city as starting point, then go to next city simultaneously
|
|
for step in range(0, self.N - 1):
|
|
# print("[step]", step)
|
|
unvisited_list = list(range(0, self.N))
|
|
# For each search path
|
|
for i in range(0, self.N):
|
|
cur_city = UCS_solutions[i][-1]
|
|
unvisited_list = list( set(range(0, self.N)) - set(UCS_solutions[i]) )
|
|
# print(unvisited_list)
|
|
closest_neighbour = -1
|
|
shortest_distance = math.inf
|
|
for j in unvisited_list:
|
|
if(self.dist(cur_city, j) < shortest_distance):
|
|
closest_neighbour = j
|
|
shortest_distance = self.dist(cur_city, j)
|
|
UCS_solutions[i].append(closest_neighbour)
|
|
|
|
for i in range(0, self.N):
|
|
self.fitness_list.append(self.fitness(UCS_solutions[i]))
|
|
|
|
self.best_solution = UCS_solutions[ self.fitness_list.index(min(self.fitness_list)) ]
|
|
self.fitness_list.append(self.fitness(self.best_solution))
|
|
|
|
return self.best_solution, self.fitness_list
|