Oto mój kod Java dla rozwiązywania Wieża Hanoi za pomocą rekurencji:Wieża Hanoi rekurencji java
/**here is a stack of N disks on the first of three poles (call
them A, B and C) and your job is to move the disks from pole A to pole B without
ever putting a larger disk on top of a smaller disk.*/
public class Hanoi {
public static void main(String[] args) {
playHanoi (2,"A","B","C");
}
//move n disks from position "from" to "to" via "other"
private static void playHanoi(int n, String from , String other, String to) {
if (n == 0)
return;
if (n > 0)
playHanoi(n-1, from, to, other);
System.out.printf("Move one disk from pole %s to pole %s \n ", from, to);
playHanoi(n-1, other, from, to);
}
}
Czy miejsce kładę metody sprawę drukowania? Czy mogę to zrobić tak:
playHanoi(n-1, from, to, other);
playHanoi(n-1, other, from, to);
System.out.printf("Move one disk from pole %s to pole %s \n ", from, to);
tak to robi ..... "printf" w pierwszym przypadku będzie pomiędzy wywołaniami funkcji, aw drugim, po dwóch wywołaniach funkcji. – Bill
uruchom go i zobacz wyjście, aby zrozumieć różnicę ... – Bill
również, pierwsza metoda jest lepsza (i poprawna), ponieważ nie powinieneś przenosić dysków za pomocą drugiego podejścia .... pomyśl dlaczego :) – Bill