The Greedy heuristic gradually constructs a tour by
repeatedly selecting the shortest edge and adding it to the tour as long as
it doesn’t create a cycle with less than N edges, or increases the degree of
any node to more than 2. We must not add the same edge twice of course.
Args:
problem (TSP): Problem to solve
Raises:
ValueError: If problem is None
Returns:
list[Solution]: Collection of solutions for the given problem
Source code in digneapy/solvers/tsp.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 | def greedy(problem: TSP, *args, **kwargs) -> list[Solution]:
"""The Greedy heuristic gradually constructs a tour by
repeatedly selecting the shortest edge and adding it to the tour as long as
it doesn’t create a cycle with less than N edges, or increases the degree of
any node to more than 2. We must not add the same edge twice of course.
Args:
problem (TSP): Problem to solve
Raises:
ValueError: If problem is None
Returns:
list[Solution]: Collection of solutions for the given problem
"""
if problem is None:
raise ValueError("No problem found in two_opt heuristic")
N = problem.dimension
distances = problem._distances
counter = Counter()
selected: set[tuple[int, int]] = set()
ordered_edges = sorted(
[(distances[i][j], i, j) for i in range(N) for j in range(i + 1, N)]
)
length = 0.0
for dist, i, j in ordered_edges:
if (i, j) in selected or (j, i) in selected:
continue
if counter[i] >= 2 or counter[j] >= 2:
continue
selected.add((i, j))
counter[i] += 1
counter[j] += 1
length += dist
if len(selected) == N:
break
_fitness = 1.0 / length
return [
Solution(
chromosome=list(range(N + 1)), objectives=(_fitness,), fitness=_fitness
)
]
|