Algorithm for NxM puzzle written in Java