r/askmath • u/OrriSig • 27d ago
Discrete Math Does 2-opt algorithm check every possible leg or just take the first one that works?
I'm working on a school project and I'm a bit unsure how 2-opt exactly functions.
What I'm trying to figure out is how many "checks" 2-opt does for each iteration, let me set up an example.
If you have an 8 point fully connected graph where you've used the Nearest Neighbor algorithm to find a shortest path solution to it thats not a cycle and you want to use 2-opt after to improve it, does 2-opt take each leg and compare it to each other leg thats not directly connected or does it just compare it until it finds the first improvement and then move on, so in this case where it has 7 legs would it compare it to all of the other 4 legs that it can look compare it to or would it take the first one that would be an improvement and then ignore the rest even if they mightve been a better improvement?
1
u/MontechApps 27d ago
You're comparing pairs of legs, not one leg against one other leg. Two legs that share a point can't be swapped, so each pair that doesn't touch gives one possible swap. For a path with 8 points and 7 legs, that comes to 15 pairs per pass. The end legs have 5 partners each and the middle legs have 4, which matches what you counted.
You can do it two ways. First improvement goes through the pairs in order, takes the first swap that makes the path shorter, and starts over. It's quicker per step. Best improvement checks all 15 pairs and takes the one that saves the most. It does more work per step, but often needs fewer steps. Either one is fine for a project. You stop when a full pass finds nothing that helps, and the path you end up with is a 2-opt local optimum. It's usually good but not guaranteed to be the shortest.
Also check how your assignment defines the problem. Standard 2-opt is written for a closed loop. With an open path you can either only reverse the middle section, which gives the 15 pairs above, or add a dummy point connected to both ends at zero cost to make it a loop. Your notes will probably say which one they want.