Home > php教程 > PHP源码 > php版螺旋矩阵(由里到外)

php版螺旋矩阵(由里到外)

PHP中文网
Release: 2016-05-26 08:21:13
Original
1459 people have browsed it


<?php
function matrix($n){
    $y = $x = ($n - 1) / 2;
    $num = 2;
    $total = pow($n, 2);
    $arr = array_fill(0, $n, array_fill(0, $n, 1));
    $i = 0;
    $limit = 1;

    while ($num <= $total) {
         for ($j = 0; $num <= $total && $j < $limit; ++$j) { 
             switch ($i) {
                 case 0 :
                     ++$y;
                     break;
                 case 1 :
                     ++$x;
                     break;
                 case 2 :
                     --$y;
                     break;
                 case 3 :
                     --$x;
                     break;
             }
             $arr[$x][$y] = $num++;
         }
         if ($i % 2 == 1) {
             ++$limit;
         }
         $i = ($i + 1) % 4;
     } 
     return $arr;
}

$arr = matrix(6);
print_r($arr);
Copy after login

                   

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template