如何实现一个顺时针的螺旋算法


int i 值可以随意

   
  int i=5;
  
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

int i=6
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11

c php

GG思密达 12 years, 6 months ago

给你个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

Your Answer