PHP " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

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

扬州沐宇科技
2024-04-26 20:06:48
PHP

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

扫码添加客服微信