This article explains how to implement clockwise printing of matrices and spiral matrices in PHP.
The example in this article describes the method of printing a matrix clockwise in PHP. Share it with everyone for your reference, the details are as follows:
Question
Enter a matrix and print out each number in clockwise order from the outside to the inside. For example, if you enter the following matrix:
1234
5678
9101112
13141516
will print out the numbers 1,2,3,4,8,12 in sequence ,16,15,14,13,9,5,6,7,11,10.
The solution
is to print in circles, as long as the loop is controlled well.
Pay attention to the situation of single row and single column.
Implementation code
function printMatrix($matrix) { $row = count($matrix); $col = count($matrix[0]); if($row == 0 || $col == 0) return $matrix; $result = array(); $left = 0;$right = $col-1; $top = 0;$bottom = $row-1; while($left<=$right && $top<= $bottom){ for($i =$left;$i<=$right;++$i){ array_push($result, $matrix[$top][$i]); } for($i =$top+1;$i<=$bottom;++$i) array_push($result, $matrix[$i][$right]); if($top!=$bottom){ for($i = $right-1;$i>=$left;--$i) array_push($result, $matrix[$bottom][$i]); } if($left!=$right){ for($i = $bottom-1;$i>$top;--$i) array_push($result, $matrix[$i][$left]); } $left++;$right--;$top++;$bottom--; } return $result; }
This article explains how PHP implements clockwise printing of matrices and spiral matrices. For more related content, please pay attention to the PHP Chinese website.
Related recommendations:
PHP learning: Predefined variable details
Teach you how to use PHP development to implement the WeChat refund function
PHP method to print binary trees in zigzag order
The above is the detailed content of PHP method to realize clockwise printing matrix and spiral matrix. For more information, please follow other related articles on the PHP Chinese website!