Home > Article > Backend Development > 顺时针方向打印矩阵解决思路
顺时针方向打印矩阵
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 /> }