search
HomeBackend DevelopmentPHP TutorialImplementation of recursive algorithm and iterative algorithm for Tower of Hanoi problem in PHP

This article introduces the recursive algorithm implementation and iterative algorithm implementation of the Tower of Hanoi problem in PHP. It has a certain reference value. Now I share it with you. Friends in need can refer to it

implementation Code


Program code address: https://github.com/ParrySMS/Exp/tree/master/ProLang/hannota

Recursive method hannoRec.php

<?php/**
 * Created by PhpStorm.
 * User: L
 * Date: 2018-4-15
 * Time: 2:07
 *//** 递归实现
 * @param $id //盘子编号
 * @param $first //起点柱子
 * @param $middle //中介柱子
 * @param $end //终点柱子
 */function hanRec($id, $first, $middle, $end,$counter){
    if ($id == 1) {
        move(1,$first,$end,$counter);
    } else {
        hanRec($id-1,$first,$end,$middle,$counter);
        move($id,$first,$end,$counter);        $counter++;
        hanRec($id-1,$middle,$first,$end,$counter);
    }
}function move($id,$from,$to,$counter){
    global $counter;    $counter++;   // echo "step: $counter, level $id from $from move to $to, <br/>";}

Iteration methodhannoIter

<?php/**
 * Created by PhpStorm.
 * User: L
 * Date: 2018-4-17
 * Time: 2:38
 */class Params{ //定义一个对象来保存参数状态
    public $id;    public $num;    public $first;    public $middle;    public $end;    public $counter;    /**
     * Params constructor.
     * @param $num
     * @param $first
     * @param $middle
     * @param $end
     * @param $counter
     */
    public function __construct($id,$num, $first, $middle, $end, $counter)
    {
        $this->id = $id;        $this->num = $num;        $this->first = $first;        $this->middle = $middle;        $this->end = $end;        $this->counter = $counter;
    }

}function hanIter($id,$num, $first, $middle, $end, $counter){
    $stack =init($id,$num, $first, $middle, $end, $counter);    while($stack){        //出栈
        $action = array_pop($stack);       // var_dump($action);
        if($action->num ==1){
            move($action->id,$action->first,$action->end,$action->counter);
        }else{            //入栈
            $next_stack = init($action->id,$action->num,$action->first, $action->middle, $action->end, $action->counter);            $stack=array_merge($stack,$next_stack);
        }
    }

}/** 入栈操作
 * @param $id //需要移动的盘子
 * @param $num //移动该盘子需要挪动的总盘子数量
 * @param $first
 * @param $middle
 * @param $end
 * @param $counter
 * @return array
 */function init($id,$num,$first, $middle, $end, $counter){
    unset($stack);    //注意入站出站顺序
    $stack = array();    //第一次回调
    $stack[] =new Params($id-1,$num-1,$middle,$first,$end,$counter);    //第二次回调
    $stack[] =new Params($id,1,$first, $middle, $end, $counter);    //第三次回调
    $stack[] =new Params($id-1,$num-1,$first,$end,$middle,$counter);    return $stack;

}/** 若在测试用例中,由于两个文件都有此 move函数,函数重名,注释掉其中一个即可 

function move($id,$from,$to,$counter){
    global $counter;
    $counter++;
   // echo "step: $counter, level $id from $from move to $to, <br/>";
}

**/

Execution time test script test.php

<?php/**
 * Created by PhpStorm.
 * User: L
 * Date: 2018-4-17
 * Time: 2:18
 */require "hannoRec.php";require "hannoIter.php";



define(&#39;TIMES&#39;, 100);
define(&#39;NUM&#39;, 10);function rowTable(){
    unset($row);    $row = array();    for ($i = 0; $i < TIMES; $i++) {    $row = getSortRow($row);
    }    foreach ($row as $r) {        print <<< TR
 <tr>
       <td>$r->iter</td>
       <td>$r->rec</td>
    </tr>
TR;
    }
}function getSortRow(array $row){
    $num = NUM;    $counter= 0;    $stime = microtime(true);
    hanIter($num, $num, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, $counter);    $etime = microtime(true);    $iterTime = 1000 * ($etime - $stime);//    echo "<br/>";
    $counter = 0;    $num = NUM;    $stime = microtime(true);
    hanRec($num, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, $counter);    $etime = microtime(true);    $recTime = 1000 * ($etime - $stime);    $row[] = (object)["iter" => $iterTime, "rec" => $recTime];    return $row;
}?><table border="1">
    <tr>
        <th>迭代 Iter/ms</th>
        <th>递归 Rec/ms</th>
    </tr>    <?php rowTable(); ?></table>

Reference

Iterative method ideas: https://wenku.baidu.com/view/dce79165b0717fd5360cdcdb.html

Related recommendations:

php Recursive function example analysis

PHP recursive algorithm simplification


The above is the detailed content of Implementation of recursive algorithm and iterative algorithm for Tower of Hanoi problem in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.