- 论坛徽章:
- 46
|
我滴- #!/usr/bin/perl -w
- use strict;
- my $n = 15;
- my @aoa;
- my($dx,$dy) = (1, 0); # 起始方向
- my($x, $y) = (0, 0); # 起始位置
- sub next {
- my($nx, $ny) = ($x+$dx, $y+$dy);
- # 过滤不在矩阵内的坐标
- if ($nx >= 0 and $ny >= 0 and $nx < $n and $ny < $n) {
- unless (defined $aoa[$nx][$ny]) {
- ($x, $y) = ($nx, $ny);
- return;
- }
- }
- for ([1,0], [0,1],[-1,0], [0,-1]) { #依次查看四个方向有无可用空位
- my($ndx, $ndy) = @$_;
- ($nx, $ny) = ($x+$ndx, $y+$ndy);
- # 过滤不在矩阵内的坐标
- next if $nx < 0 or $ny < 0 or $nx >= $n or $ny >= $n;
- unless (defined $aoa[$nx][$ny]) {
- ($x, $y) = ($nx, $ny);
- ($dx, $dy) = ($ndx, $ndy);
- return;
- }
- }
- }
- for (1 .. $n*$n) {
- $aoa[$x][$y] = $_;
- &next;
- }
- for my $array_ref (@aoa) {
- printf " %3d", $_ for @$array_ref;
- print "\n";
- }
复制代码 |
|