my $n = shift; my @AoA; my $flip = 0; my @directions = ( 'right', 'down', 'left', 'up'); my $direction = $directions[ $flip % 4 ]; my ($x, $y) = (0, 0); for ( 1 .. $n * $n ){ $AoA[ $x ][ $y ] = $_; $flip++ if 'right' eq $direction and ( $x == $n - 1 or $AoA[ $x + 1 ][ $y ]); $flip++ if 'down' eq $direction and ( $y == $n - 1 or $AoA[ $x ][ $y + 1 ]); $flip++ if 'left' eq $direction and ( $x == 0 or $AoA[ $x - 1 ][ $y ]); $flip++ if 'up' eq $direction and ( $AoA[ $x ][ $y - 1 ]); $direction = $directions[ $flip % 4 ]; $x++ if 'right' eq $direction; $y++ if 'down' eq $direction; $x-- if 'left' eq $direction; $y-- if 'up' eq $direction; } for my $y (0..$n-1){ for my $x (0..$n-1){ printf "%5d ", $AoA[$x][$y]; # for some value of 5 } print "\n"; }