Home  >  Article  >  Backend Development  >  顺时针方向打印矩阵,该怎么处理

顺时针方向打印矩阵,该怎么处理

WBOY
WBOYOriginal
2016-06-13 11:46:41840browse

顺时针方向打印矩阵
http://blog.csdn.net/wusuopubupt/article/details/12788249
在这里看到的。

<?php<br />/**<br /> * @author:wusuopubupt<br /> * @date:2013-10-16<br /> * @from:http://ac.jobdu.com/problem.php?pid=1391<br /> * <br /> * Print matrix in clockwise<br /> * */<br />$matrix = array<br />(<br />	array(1,2,3,4),<br />	array(5,6,7,8),<br />	array(9,10,11,12),<br />	array(13,14,15,16),<br />	array(17,18,19,20)<br />);<br /><br />print_matrix($matrix);<br /><br />function print_matrix($arr) {<br />	$top = 0;<br />	$left = 0;<br />	$right = count($arr[0])-1;<br />	$bottom  = count($arr)-1;<br />	<br />	while ($left != $right && $top != $bottom) {<br />		//top<br />		for($j = $left; $j <= $right; $j++) {<br />			echo $arr[$top][$j]." ";<br />		}<br />		$top++;<br />		<br />		//right<br />		for($i = $top; $i <= $bottom; $i++) {<br />			echo $arr[$i][$right]." ";<br />		}<br />		$right--;<br />		<br />		//bottom<br />		for($j = $right; $j >= $left; $j--) {<br />			echo $arr[$bottom][$j]." ";<br />		}<br />		$bottom--;<br />		<br />		//left<br />		for($i = $bottom; $i >= $top; $i--) {<br />			echo $arr[$i][$left]." ";<br />		}<br />		$left++;<br />	}<br />}

为啥输出结果是这样的呢?1 2 3 4 8 12 16 20 19 18 17 13 9 5 6 7  11 15 14 10
------解决方案--------------------
可能是因为每个数组的长度都相同才可以吧。 上下左右 不断的减1.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn