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

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

PHP中文网
PHP中文网Original
2016-05-26 08:21:131492browse


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

                   

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
Previous article:输出数据跟前端实现通信Next article:php爬美女照