Home  >  Article  >  Backend Development  >  Example of how to implement clockwise printing matrix (spiral matrix) in PHP

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

韦小宝
韦小宝Original
2018-01-13 11:54:342078browse

This article mainly introduces the method of PHP to realize clockwise printing matrix (spiral matrix), involving the related operation skills of PHP based on array traversal, operation simulation printing to realize the spiral matrix function, interested in PHP Friends can refer to this article.

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:

1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

will print out the numbers 1,2,3,4,8,12,16,15,14,13,9,5,6,7,11 in sequence ,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

<?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;
}

The above is all the content of this article, I hope it can help everyone learn! !

Related recommendations:

PHP method to determine whether a binary tree is symmetrical

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

php stringReversal often encountered in interviews

The above is the detailed content of 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!

Statement:
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