Home > Article > Backend Development > Code example for php to print matrix clockwise
The content of this article is about the code example of PHP clockwise printing matrix. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
1. Take out the number of rows and columns, row, col, and the number of turns is (smaller value - 1)/2 1
2. The outer loop controls the number of turns. There are four inner for loops, i
3. The first for loop, from left to right, j=i;j 4. The second for loop, from top to bottom, k=i 1;k 5. The third loop, from right to left, m=col-2-i;m>=i&&row-1-i!=i;m-- arr[row-1-i][m]//row-1- When i!=i is a single line, it is only printed once 6. The fourth loop, from bottom to top, n=row-2-i;n>=i&&col-1-i!=i;n- - arr[n][i] The above is the detailed content of Code example for php to print matrix clockwise. For more information, please follow other related articles on the PHP Chinese website!<?php
$arr=array();
$flag=0;
for($i=0;$i<2;$i++){
$flag=$i*2;
for($j=0;$j<2;$j++){
$flag++;
$arr[$i][]=$flag;
}
}
var_dump($arr);
//顺时针打印矩阵
function printMatrix($arr){
$res=array();
$row=count($arr);
$col=count($arr[0]);
$circle=intval((($row>$col ? $col : $row)-1)/2+1);
for($i=0;$i<$circle;$i++){
//转圈开始
//从左到右
for($j=$i;$j<=$col-1;$j++){
$t=$arr[$i][$j];
if(in_array($t,$res)) continue;
$res[]=$t;
}
//从上到下
for($k=$i+1;$k<$row-$i;$k++){
$t=$arr[$k][$col-$i-1];
if(in_array($t,$res)) continue;
$res[]=$t;
}
//从右到左
for($m=$col-$i-2;$m>=$i;$m--){
$t=$arr[$row-$i-1][$m];
if(in_array($t,$res)) continue;
$res[]=$t;
}
//从下到上
for($n=$row-$i-2;$n>$i;$n--){
$t=$arr[$n][$i];
if(in_array($t,$res)) continue;
$res[]=$t;
}
}
return $res;
}
$res=printMatrix($arr);