题目:http://www.spoj.com/problems/SPTTRN3/
题意:输出螺旋的图案,图案规则是先顺时针画一圈星号,但是首尾不能相连,然后在第二层中隔两点,接着是逆时针画圈
具体代码如下:
<?php
$debug = false;
$file = STDIN;
if ($debug)
{
$file = fopen("./spoj.txt", "r");
}
$t = trim(fgets($file));
while ($t--)
{
$line = trim(fgets($file));
$n = intval($line);
solve($n);
if (0 != $t) echo PHP_EOL;
}
if ($debug) fclose($file);
function solve($n)
{
$matrix = array();
$tmp = array();
$tmp = array_pad($tmp, $n, '.');
$matrix = array_pad($matrix, $n, $tmp);
$clockdx = array(0, 1, 0, -1);
$clockdy = array(1, 0, -1, 0);
$arr[] = array($clockdx, $clockdy);
$anticlockdx = array(1, 0, -1, 0);
$anticlockdy = array(0, 1, 0, -1);
$arr[] = array($anticlockdx, $anticlockdy);
$cur = 0;
$curdir = 0;
$x = 0; $y = 0;
$loop = (int)($n / 4);
$remain = $n % 4;
for ($i = 0; $i < $loop; $i++)
{
$curx = $x; $cury = $y;
while (true)
{
$matrix[$curx][$cury] = '*';
$newx = $curx + $arr[$cur][0][$curdir]; $newy = $cury + $arr[$cur][1][$curdir];
//echo 'curx:', $curx, ' cury:', $cury, ' newx:', $newx, ' newy:', $newy, PHP_EOL;
if ($newx == $x && $newy == $y)
{
$matrix[$curx][$cury] = '.';
$curx -= $arr[$cur][0][$curdir];
$cury -= $arr[$cur][1][$curdir];
break;
}
if ($newx < 0 + $i * 2 || $newx >= $n - $i * 2 || $newy < 0 + $i * 2 || $newy >= $n - $i * 2)
{
$curdir = ($curdir + 1) % 4;
continue;
}
$curx = $newx; $cury = $newy;
}
if ($loop - 1 != $i)
{
$curdir = ($curdir + 1) % 4;
$curx = $curx + $arr[$cur][0][$curdir]; $cury = $cury + $arr[$cur][1][$curdir];
$matrix[$curx][$cury] = '*';
$x = $curx + $arr[$cur][0][$curdir]; $y = $cury + $arr[$cur][1][$curdir];
$cur = ($cur + 1) % 2;
}
}
//echo 'remain:', $remain, PHP_EOL;
if (0 !== $remain)
{
$curdir = ($curdir + 1) % 4;
$curx = $curx + $arr[$cur][0][$curdir]; $cury = $cury + $arr[$cur][1][$curdir];
$matrix[$curx][$cury] = '*';
$x = $curx + $arr[$cur][0][$curdir]; $y = $cury + $arr[$cur][1][$curdir];
$cur = ($cur + 1) % 2;
$curx = $x; $cury = $y;
while ($remain--)
{
while (true)
{
$matrix[$curx][$cury] = '*';
$newx = $curx + $arr[$cur][0][$curdir]; $newy = $cury + $arr[$cur][1][$curdir];
//echo 'curx:', $curx, ' cury:', $cury, ' newx:', $newx, ' newy:', $newy, PHP_EOL;
if ($newx < 0 + $i * 2 || $newx >= $n - $i * 2 || $newy < 0 + $i * 2 || $newy >= $n - $i * 2)
{
$curdir = ($curdir + 1) % 4;
break;
}
$curx = $newx; $cury = $newy;
}
}
}
//var_dump($matrix);
output($matrix);
}
function output($matrix)
{
$ans = '';
$size = count($matrix);
for ($i = 0; $i < $size; $i++)
{
for ($j = 0; $j < $size; $j++)
{
$ans .= $matrix[$i][$j];
}
$ans .= PHP_EOL;
}
echo $ans;
}
?>