日期:2014-05-16  浏览次数:20413 次

顺时针方向打印矩阵
http://blog.csdn.net/wusuopubupt/article/details/12788249
在这里看到的。
<?php
/**
 * @author:wusuopubupt
 * @date:2013-10-16
 * @from:http://ac.jobdu.com/problem.php?pid=1391
 * 
 * Print matrix in clockwise
 * */
$matrix = array
(
array(1,2,3,4),
array(5,6,7,8),
array(9,10,11,12),
array(13,14,15,16),
array(17,18,19,20)
);

print_matrix($matrix);

function print_matrix($arr) {
$top = 0;
$left = 0;
$right = count($arr[0])-1;
$bottom  = count($arr)-1;

while ($left != $right && $top != $bottom) {
//top
for($j = $left; $j <= $right; $j++) {
echo $arr[$top][$j]." ";
}
$top++;

//right
for($i = $top; $i <= $bottom; $i++) {
echo $arr[$i][$right]." ";
}
$right--;

//bottom
for($j = $right; $j >= $left; $j--) {
echo $arr[$bottom][$j]." ";
}
$bottom--;

//left
for($i = $bottom; $i >= $top; $i--) {
echo $arr[$i][$left]." ";
}
$left++;
}
}

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