php中的矩阵排列问题

Cen*_*ion 10 php algorithm logic

我想知道一些解决这个问题的方法.

给出一个数字,比方说16,你必须以这种方式排列矩阵

1  2  3  4
12 13 14 5
11 16 15 6
10 9  8  7
Run Code Online (Sandbox Code Playgroud)

语言没关系,(最好是PHP);

sha*_*mar 7

[编辑:更新]如果语言无关紧要:

请访问:http://rosettacode.org/wiki/Spiral_matrix


在PHP中:

干得好:

<?php
function getSpiralArray($n)
{
    $pos = 0;
    $count = $n;
    $value = -$n;
    $sum = -1;

    do
    {
        $value = -1 * $value / $n;
        for ($i = 0; $i < $count; $i++)
        {
            $sum += $value;
            $result[$sum / $n][$sum % $n] = $pos++;
        }
        $value *= $n;
        $count--;
        for ($i = 0; $i < $count; $i++)
        {
            $sum += $value;
            $result[$sum / $n][$sum % $n] = $pos++;
        }
    } while ($count > 0);

    return $result;
}

function PrintArray($array)
{
    for ($i = 0; $i < count($array); $i++) {
        for ($j = 0; $j < count($array); $j++) {
            echo str_pad($array[$i][$j],3,' ');
        }
        echo '<br/>';
    }
}

$arr = getSpiralArray(4);
echo '<pre>';
PrintArray($arr);
echo '</pre>';
?>
Run Code Online (Sandbox Code Playgroud)

  • +1有趣地使用$ value作为描述当前方向的向量.一个"虚拟"-1表示无信息变量名$ value,$ count (2认同)