Answers
给你个php版算法:
<?php
function getSpiralArray($n)
{
$pos = 1;
$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 "\n";
}
}
$arr5 = getSpiralArray(5);
PrintArray($arr5);
$arr6 = getSpiralArray(6);
PrintArray($arr6);
?>
截图:
迎风射三丈
answered 12 years, 6 months ago