java - Hanoi Towers, working but not supposed to -
so have classical hanoi problem, im getting recursion thing, , doozie! functioning, don't understand how be! i've understood it, n, print "from + " going " + thru", happen each time n approaches 1. 1 think @ n=1, code stop, , yet printouts of "thru + " going " + to" (last printout). if n=1 terminating condition, how can possibly last part of code "for free?".
i expected code @ least execute last printout on every iteration, no! also, examples of include 2 recursive calls, works fine one! hell going on? how code execute, step step? have misunderstood basic fact recursive methods? (compiled on eclipse compiler).
public static void hanoi(char from, char to, char thru, int n) { if (n==1) { system.out.println(from + " going " + to); } else { system.out.println (from + " going " + thru); hanoi(from, to, thru, n-1); system.out.println (thru + " going " + to); } }
have misunderstood basic fact recursive methods?
it sounds have. seem have impression that, though call method several times, method exits once. in truth, every time hit line:
system.out.println (from + " going " + thru); <-- line hanoi(from, to, thru, n-1); system.out.println (thru + " going " + to);
... must hit later line @ point after recursive call completes:
system.out.println (from + " going " + thru); hanoi(from, to, thru, n-1); system.out.println (thru + " going " + to); <-- line
n == 1
"terminating condition" in sense not make additional recursive call. however, "if" statement still has code in it:
if (n==1) { system.out.println(from + " going " + to); }
this code run part of final condition, not call hanoi
method again. however, end of recursive calls. each other time hanoi
called before point, there still method call on stack, , method calls need complete.
system.out.println (from + " going " + thru); hanoi(from, to, thru, n-1); <-- if `n-1` here `1`, you'd still have complete following line. system.out.println (thru + " going " + to);
Comments
Post a Comment