How to print the matrix clockwise

Source: Internet
Author: User
Print the matrix clockwise at http://blog.csdn.net/wusuopubupt/article/details/41088249here. & Lt ;? Php/** & nbsp; * & nbsp; @ author: wusuopubupt & nbsp; * & nbsp; @ date: clockwise print matrix
Http://blog.csdn.net/wusuopubupt/article/details/12788249
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 is the output like this? 1 2 3 4 8 12 16 20 19 17 13 9 5 6 7 11 15 14 10
------ Solution --------------------
It may be because the length of each array is the same. The upper, lower, and left sides are constantly reduced by 1.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.