Home >Backend Development >PHP Tutorial >An example of how to implement clockwise printing matrix (spiral matrix) in PHP
This article mainly introduces the method of PHP to realize clockwise printing matrix (spiral matrix), and involves the related operation skills of PHP to realize the spiral matrix function based on array traversal and operation simulation printing. Friends in need can refer to the following
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 it in clockwise order from outside to inside. Out each number, for example, if you enter the following matrix:
2 | 3 | 4 | |
6 | 7 | 8 | |
10 | 11 | 12 | |
14 | 15 | 16 |
The solution is to print in circles, as long as the loop is controlled well can.
Pay attention to the situation of single row and single column.Implementation code
<?php 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; }
You may be interested Article:
Explanation on how to use PHP to determine whether a binary tree is symmetricalAn example of how PHP uses one line of code to delete all files in a directoryExplanation on how PHP obtains the first non-repeating character in the character stream
The above is the detailed content of An example of how to implement clockwise printing matrix (spiral matrix) in PHP. For more information, please follow other related articles on the PHP Chinese website!