Grand temple approach

please help me how to approach the question.I have understood the problem but unable to approach the main logic.
please elaborate conceptually instead of showing the code.