编写一个程序,以螺旋线的形式枚举规则网格上的点。输出应该是各点(行-大)的指数,螺旋应该从0开始,逆时针方向进行。
下面是这个问题的一个例子:
发布于 2014-07-16 13:53:11
w=4;h=3;Flatten@NestList[Reverse@Transpose@Rest@#&,Partition[Range[w h],w],2Min[w,h]-2][[;;,1]]-1
2*min(w,h)-2
.发布于 2014-07-16 09:02:38
w=8,h=8
{for(a=[0],x=y=b=r=t=l=s=0;a.length<w*h;){if(s==0&&x+r+1==w&&++b+1||s==1&&y+t+1==h&&++r+1||s==2&&x==l&&++t+1||s==3&&y==b&&++l+1)s=(s+1)%4
s==0&&++x+1||s==1&&++y+1||s==2&&--x+1||--y
a.push(x+w*y)}alert(a.join(' '))}
不打高尔夫球的:
w = 8 // width of grid
h = 8 // height of grid
for(a = [0], // array
x = // x pos
y = // y pos
b = // bottom rows done
r = // right rows done
t = // top rows done
l = // left rows done
s = 0; // current side 0: b, 1: r, 2: t, 3: l
a.length < w*h;) {
if (s==0 && x+r+1==w && ++b+1 ||
s==1 && y+t+1==h && ++r+1 ||
s==2 && x==l && ++t+1 ||
s==3 && y==b && ++l+1 ){
s=(s+1)%4
}
s==0 && ++x+1 ||
s==1 && ++y+1 ||
s==2 && --x+1 ||
--y
a.push(x+w*y)
}
alert(a.join(' '))
代码在w
和h
中设置网格大小。它将当前坐标存储在x
和y
中。它朝s
方向导航,并在b
、r
、t
和l
中存储已经填充的行数。
https://codegolf.stackexchange.com/questions/34591
复制相似问题