Threw together a little prototype using the neat or-tools optimization library from Google.
It uses G00 (move) commands as delimiters to separate a file into re-orderable segments and then solves traveling salesman to minimize the distance spent on travel moves between those segments. Some but unfortunately not all of the gcode I’m interested in follows that rule; straight lines longer than a certain length would be another easy heuristic to split on.
This Inkscape tracing of a diffusion-reaction pattern erases itself with vertical travel moves.
But if we optimize it without reversing any of the segments (traversing them all start-to-end) then we get
And if we duplicate all the segments with reversed versions (tracing the line end-to-start instead of start-to-end) and tell the optimizer that the duplicate is mutually exclusive with its twin then we get the very neat
Artistically the second one happens to look the best on sand even though it travels a bit more.
diffuse_ortools2.gcode (713.1 KB)