Code for poj.org no.3984 puzzle problem