首页 > 代码库 > 汉诺塔问题php解决

汉诺塔问题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();?>

  

汉诺塔问题php解决