回型打印练习

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

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

<?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>
			<?php
			echo $html?>
</body>
</html>
分析补充:

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

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

走完的时候正好就是判断转向的节点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值