I'm trying to do a certain simulation related to the toric code and I'm looking for an algorithm that connects $2n$ points ($n \in \mathbb Z_+$) in $\mathbb R^2$ with line segments with the following restrictions:
- Length of the all segments joined together has to be minimal.
- One point can be a part of only one line segment.
- Line segments cannot intersect.
We can assume that the $2n$ points all lie on a square grid as shown in the following figure.
Someone on Stack Overflow considered a similar question but the answers there are not really satisfying or authoritative. However, I will reuse the picture from there to clarify what I want:
Is there a reasonable non-brute force algorithm for this problem? I wonder if the Travelling Salesman Problem can somehow be modified to fit this situation. Someone also mentioned K-means clustering on the Stack Overflow question but I'm not sure how that's relevant.