A non-recursive solution to this problem?

I am referring to the following problem- Indian National Olympiad in Informatics - Online Programming Contest - IARCS
(NUMROUTE problem from the ico online judge). I coded up a solution using recursion, which works fine for small inputs, but as expected gives SEGFAULT for large inputs. Can anyone suggest a method that does not employ recursion?