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();
    ?>
    

      

  • 相关阅读:
    Nginx:rewrite / if / return / set 和变量 (转载)
    【Aming】win10用anaconda3安装 TensorFlow
    git
    webpack(3)
    webpack(2)
    webpack(1)
    json
    Aliyun搭建svn服务器外网访问报错权限配置失败错误
    阿里云ECS服务器,mysql无法外网访问
    mysql出现 Unknown column 'Password' in 'field list'
  • 原文地址:https://www.cnblogs.com/taijun/p/4113055.html
Copyright © 2011-2022 走看看