function hanoi($n, $start, $end, $temp) {
if ($n === 1) {
echo "Move disk 1 from $start to $end\n";
} else {
hanoi($n - 1, $start, $temp, $end);
echo "Move disk $n from $start to $end\n";
hanoi($n - 1, $temp, $end, $start);
}
}
$n = 3; // 汉诺塔的层数
hanoi($n, 'A', 'C', 'B');
输出:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C