The Shortest Edge Greedy heuristic for TSP
It 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192 | def shortest_edge(problem: TSP, start_node: int = 0) -> list[Solution]:
"""The Shortest Edge Greedy heuristic for TSP
It 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
"""
try:
N = problem.dimension
if not (0 <= start_node < N):
raise ValueError(f"start_node must be in [0, {N}), got {start_node}")
distances = problem._distances
parent = list(range(N))
rank = [0] * N
def find(x: int) -> int:
root = x
while parent[root] != root:
root = parent[root]
while parent[x] != root: # path compression
parent[x], x = root, parent[x]
return root
def union(a: int, b: int) -> None:
ra, rb = find(a), find(b)
if rank[ra] < rank[rb]:
ra, rb = rb, ra
parent[rb] = ra
if rank[ra] == rank[rb]:
rank[ra] += 1
ordered_edges = sorted([
(distances[i][j], i, j) for i in range(N) for j in range(i + 1, N)
])
length = np.float64(0.0)
selected_edges = 0
degree = [0] * N
adjacency: list[list[int]] = [[] for _ in range(N)]
for dist, i, j in ordered_edges:
if degree[i] >= 2 or degree[j] >= 2:
continue
root_i, root_j = find(i), find(j)
if root_i == root_j:
if selected_edges != N - 1:
continue
union(i, j)
degree[i] += 1
degree[j] += 1
adjacency[i].append(j)
adjacency[j].append(i)
length += dist
selected_edges += 1
if selected_edges == N:
break
tour = reconstruct_tour(adjacency=adjacency, start_node=start_node, n_nodes=N)
_fitness = 1.0 / length
return [
Solution(
variables=tour,
objectives=(_fitness,),
fitness=_fitness,
constraints=(0,),
)
]
except Exception as e:
raise RuntimeError(
f"Cannot solve TSP in shortest_edge because an exception was raised. Cause {e}"
)
|