zoukankan      html  css  js  c++  java
  • 汉诺塔问题php解决

    面向过程解决

    <?php 
    function hanio($n,$x,$y,$z){//把n个盘子,按照要求从x移到z,y是中介
    	//递归跳出条件
    	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/>";
    }
    
    hanio(2, 'A', 'B', 'C');
    ?>
    

      面向过程写

    <?php 
    class Hanio{
    	private $n;//规模
    	private $start;//起始柱子
    	private $mediator;//中介柱子
    	private $goal;//目标柱子
    	private $format = '把%d从%s移动到%s';
    	public function __construct($n,$start,$mediator,$goal){
    		$this->n = $n;
    		$this->start = $start;
    		$this->mediator = $mediator;
    		$this->goal = $goal;
    	}
    	
    	//单个盘移动
    	private function move($n,$start,$goal){
    		printf($this->format,$n,$start,$goal);
    		echo "<br/>";
    	}
    	
    	public function getResult(){
    		$this->handle($this->n,$this->start,$this->mediator,$this->goal);
    	}
    	
    	private function handle($n,$x,$y,$z){
    		//递归跳出条件
    		if($n==1){
    			$this->move($n, $x, $z);
    		}else{
    			//这三部是核心
    			$this->handle($n-1, $x, $z, $y);
    			$this->move($n, $x, $z);
    			$this->handle($n-1, $y, $x, $z);
    		}
    	}
    	
    }
    
    class Client{
    	public static function main(){
    		$hanio = new Hanio(4, 'A', 'B', 'C');
    		$hanio->getResult();
    	}
    }
    
    Client::main();
    ?>
    

      

  • 相关阅读:
    推荐给新手gopher的一些书籍
    flask中路由处理
    flask中间件之请求扩展
    Chrome调试技巧
    iconfont 使用
    @font-face 使用过程
    SEO
    数据结构与算法2-4 队列
    数据结构与算法2-4 堆栈链式存储
    软件推荐--Sublime Text3常用快捷键查询(不断更新ing)
  • 原文地址:https://www.cnblogs.com/taijun/p/4113055.html
Copyright © 2011-2022 走看看