在网上看到一题,打印螺旋数列。给定n,螺旋数列包含n*n个元素,排列在n*n的矩形内。1至n*n的整数由外向内螺旋增加。
例如,n=1,数列为1
n=2,数列为
12
43
n=3,数列为
123
894
765
写了下面的算法,可以实现。但应该有更简便的算法。
object First { def main(args:Array[String]) { val n:Int =args(0).toInt val s = new Spiral(n) for ( ary<-s.numAry ) { for ( elem<-ary ) { print(elem) print(' ') } println() } } } class Spiral ( val num:Int ) { val numAry:Array[Array[Int]]=Array.fill(num,num)(0) fill() def fillRight(row:Int,col:Int,value:Int):(Int,Int,Int) = { //printf("fillRight %d, %d, %d /n", row,col,value) var r=row var c=col var v=value while( c < num && numAry(r)(c)==0) { numAry(r)(c)=v v+=1 c+=1 } (r,c,v) } def fillDown(row:Int,col:Int,value:Int):(Int,Int,Int) = { //printf("fillDown %d, %d, %d /n", row,col,value) var r=row var c=col var v=value while(r < num && numAry(r)(c)==0) { numAry(r)(c)=v v+=1 r+=1 } (r,c,v) } def fillLeft(row:Int,col:Int,value:Int):(Int,Int,Int) = { //printf("fillLeft %d, %d, %d /n", row,col,value) var r=row var c=col var v=value while(c >= 0 && numAry(r)(c)==0) { numAry(r)(c)=v v+=1 c-=1 } (r,c,v) } def fillUp(row:Int,col:Int,value:Int):(Int,Int,Int) = { //printf("fillUp %d, %d, %d /n", row,col,value) var r=row var c=col var v=value while(r >= 0 && numAry(r)(c)==0) { numAry(r)(c)=v v+=1 r-=1 } (r,c,v) } def fill() { var value=1 var col=0 var row=0 var t:(Int,Int,Int)=(0,0,0) while( value <= num * num ) { t=fillRight(row,col,value) row=t._1 + 1 col=t._2 - 1 value=t._3 t=fillDown(row,col,value) row=t._1 - 1 col=t._2 - 1 value=t._3 t=fillLeft(row,col,value) row=t._1 - 1 col=t._2 + 1 value=t._3 t=fillUp(row,col,value) row=t._1 + 1 col=t._2 + 1 value=t._3 } } }
执行结果:
D:/tmp>scalac first.scala D:/tmp>scala -classpath . First 1 1 D:/tmp>scala -classpath . First 2 12 43 D:/tmp>scala -classpath . First 3 123 894 765 D:/tmp>scala -classpath . First 4 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 D:/tmp>scala -classpath . First 5 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9 D:/tmp>scala -classpath . First 6 1 2 3 4 5 6 20 21 22 23 24 7 19 32 33 34 25 8 18 31 36 35 26 9 17 30 29 28 27 10 16 15 14 13 12 11