美文网首页
PHP汉诺塔

PHP汉诺塔

作者: 牍中玉的小木屋 | 来源:发表于2019-12-05 21:05 被阅读0次

<?php
/**
 * Created by PhpStorm.
 * User: liufeng
 * Date: 2019/12/4
 * Time: 11:14
 */

/**
 * 汉诺塔问题( 积木,借助"中间柱",从 "源柱" 移动到 "目标柱" )
 * @param $n 积木的数量
 * @param $x 源柱
 * @param $y 中间柱
 * @param $z 目标柱
 */
function hanio($n, $x, $y, $z)
{
    // 递归的退出条件
    if ($n == 1) {
        move($n, $x, $z);
    } else {
        hanio($n - 1, $x, $z, $y);
        move($n, $x, $z);
        hanio($n - 1, $y, $x, $z);
    }
}

function move($n, $x, $y)
{
    $format = '第 %d 个数: 从 %s 移动到 %s';
    printf($format, $n, $x, $y);
    echo '<br>';
}

/**************  计算使用时间  ******************/
$start_time = microtime(true);

$num = 3;
hanio($num, 'A', 'B', 'C');

$end_time = microtime(true);

echo '<hr>脚本执行时间 = ' . (($end_time - $start_time) * 1000 * 1000) . ' 微秒';

相关文章

网友评论

      本文标题:PHP汉诺塔

      本文链接:https://www.haomeiwen.com/subject/qdpjgctx.html