首页 > 代码库 > 汉诺塔问题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解决
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。