Better algorithm to solve the problem

I need to write C++ code to solve the problem below.
I can do it easily by using four "for" loops and check for the three conditions.
However, I think that is not an optimum algorithm.
Do you have an idea to solve it efficiently or better?
Thank you.

Link to the image problem: http://i.imgur.com/sCHdG6Z.png
Topic archived. No new replies allowed.