Tri-Hexagonal Puzzle - Algorithm?

Can someone help me to deduce the algorithm for N4 Problem - CodeChef problem?