Home > Backend Development > PHP Tutorial > An example of how to implement clockwise printing matrix (spiral matrix) in PHP

An example of how to implement clockwise printing matrix (spiral matrix) in PHP

jacklove
Release: 2023-04-02 08:24:02
Original
1961 people have browsed it

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:


##12 34##5913 will print out the numbers 1,2,3,4,8,12,16,15,14,13, 9,5,6,7,11,10.
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;
}
Copy after login

You may be interested Article:

Explanation on how to use PHP to determine whether a binary tree is symmetrical


An example of how PHP uses one line of code to delete all files in a directory


Explanation 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template