PHP

使用递归函数解决PHP中的汉诺塔问题

小樊
84
2024-04-26 20:06:48
栏目: 编程语言

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

0
看了该问题的人还看了