回型打印练习

来源:互联网 发布:网上买电影票软件 编辑:程序博客网 时间:2024/06/05 12:44

之前写过一次这样回型打印的程序,可是代码不知道丢哪里了。

最新心血来潮,换了个算法重新写了一次。详细分析,就下次在写了。

<?php/** * 面向对象回型字打印 * @author RaidNight *  */class Circle {public $path = array ();public $_rows;public function __construct($rows) {$this->_rows = $rows;$max = $rows;$max_map = array ();for($max; $max > 0; $max --) {$max_map [] = $max;$max_map [] = $max;}unset ( $max_map [0] );$direction_index = - 1;$directions = array ('right', 'down', 'left', 'up' );$point = array ('x' => - 1, 'y' => 0, 'v' => 0 );foreach ( $max_map as $max ) {$direction_index ++;for($i = 0; $i < $max; $i ++) {$point = $this->next ( $point, $directions [$direction_index % 4] );$this->path [] = $point;}}}private function next($point, $direction) {switch ($direction) {case 'right' :$point ['x'] ++;break;case 'down' :$point ['y'] ++;break;case 'left' :$point ['x'] --;break;case 'up' :$point ['y'] --;break;}$point ['v'] ++;return $point;}public function to_map() {$temp=array();foreach ( $this->path as $point ) {$temp[$point ['x']] [$point ['y']] = $point ['v'];}return $temp;}public function to_html(){$temp = $this->to_map();$html='<ul style="width:'.($this->_rows*40).'px">';for($y = 0; $y < $this->_rows; $y ++) {for($x = 0; $x < $this->_rows; $x ++) {$html .= '<li>' . $temp [$x] [$y] . '</li>';}}return $html.'</ul>';}}for($i=1;$i<30;$i++){$circle = new Circle( $i );$html.=$circle->to_html();$html.='<hr>';}?>

<html><head><style>ul li {float: left;width: 40px;height: 40px;}hr{clear:both;}</style></head><body><?phpecho $html?></body></html>
分析补充:

这是三行三列的时候的显示。转向步数分析,行数为 $n时,总转向次数其实是 $n*2-1,每一步的步数是, $n,$n-1,$n-1,$n-2,$n-2,....,2,2,1,1。

按照预设好得,每次的最大步数,填充,也就是map_max的保存的数组。

走完的时候正好就是判断转向的节点。