Here is untested code. (It does run the two examples correctly,
though). If you see any problems, let me know.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import jav
Since the number of moves must be optimal, this seems to be a search
problem. A-Star is the right search algorithm. This is an algorithm
that's somewhere between depth first and breadth first. It expands the
tree according to a heuristic that you choose, which can shrink the
run time enormously.