Print the matrix in clockwise direction
http://blog.csdn.net/wusuopubupt/article/details/12788249
To see here.
/**
* @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 + +;
}
}
Why does the output result be like this? 1 2 3 4 8 12 16 20 19 18 17 13 9 5 6 7 11 15 14 10
Share to: more
------Solution--------------------
Maybe it's because each array has the same length. And up and down around the constant minus 1.