Count cycles, do not search
transcript
A garage has cars in bays, and one bay is empty. One move swaps the empty bay with any car. What is the fewest moves to sort them?
Follow each bay to the bay its car belongs in. The bays fall into cycles. Then add up the cost of each cycle.
A cycle with the empty bay costs its length minus one. Any other cycle costs its length plus one. The empty bay must enter it, and leave it.
Bays zero, two and one hold one cycle of two cars. The empty bay is already in place. So the cost is two plus one: three moves.
Do not use length minus one for every cycle. That answer is one move for this garage. The true answer is three moves.
Walk each cycle once, and mark its bays as seen. Every bay is visited a single time. So a hundred thousand bays are easy.
Prove the rule before you code. Then test it against brute force. Full breakdown in the lecture.