参考答案:
<?php
function n_at($N, $r, $c, $s=1){
$v = 0;
if($c==1){
$v = $s + ($r-1);
}else if($r==$N){
$v = $s + ($N-1) + ($c-1);
}else if($c==$N){
$v = $s + ($N-1) + ($N-1) + ($N-$r);
}else{
$v = $s+($N-1)*3 + ($N-$c);
}
return $v;
}
function print_square($N){
$o = ($N+1)/2;
for($r=1; $r<=$N; $r++){
for($c=1; $c<=$N; $c++){
$n_loop = max(abs($r-$o),abs($c-$o));
$n_size = $n_loop*2 + 1;
$ir = ($r-$o) + ($n_size+1)/2;
$ic = ($c-$o) + ($n_size+1)/2;
$s = $N*$N - $n_size*$n_size+1;
$v = n_at($n_size, $ir, $ic, $s);
printf("%3d",$v);
}
print("\n");
}
}
print_square(5);
?>