1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| object SpiralOrder { def main(args: Array[String]): Unit = { println( spiralOrder( Array[Array[Int]]( Array[Int](1, 2), Array[Int](10, 3), Array[Int](9, 4), Array[Int](8, 5), Array[Int](7, 6) ) ) )
println( spiralOrder( Array[Array[Int]]( Array[Int](1, 2, 3), Array[Int](4, 5, 6), Array[Int](7, 8, 9), Array[Int](10, 11, 12), Array[Int](13, 14, 15) ) ) )
println( spiralOrder( Array[Array[Int]]( Array[Int](1, 2, 3, 4), Array[Int](5, 6, 7, 8), Array[Int](9, 10, 11, 12) ) ) )
println( spiralOrder( Array[Array[Int]]( Array[Int](1, 2, 3, 4, 5, 6), Array[Int](7, 8, 9, 10, 11, 12), Array[Int](13, 14, 15, 16, 17, 18), Array[Int](19, 20, 21, 22, 23, 24), Array[Int](25, 26, 27, 28, 29, 30) ) ) ) }
def spiralOrder(matrix: Array[Array[Int]]): List[Int] = { val list = new ListBuffer[Int]() val m = matrix.length val n = matrix(0).length
scala.util.control.Breaks.breakable(for (i <- 0 until (Math.min(m, n) + 1) / 2) { val start = (i, i) val topRight = (i, n - i - 1) val lowRight = (m - i - 1, n - i - 1) val lowLeft = (m - i - 1, i)
if (lowRight._1 == start._1) { for (l <- start._2 until topRight._2 + 1) { list += matrix(start._1)(l) } scala.util.control.Breaks.break() } else if (lowRight._2 == start._2) { for (l <- topRight._1 until lowRight._1 + 1) { list += matrix(l)(topRight._2) } scala.util.control.Breaks.break() } else { for (l <- start._2 until topRight._2 + 1) { list += matrix(start._1)(l) }
for (l <- topRight._1 + 1 until lowRight._1 + 1) { list += matrix(l)(topRight._2) }
for (l <- lowRight._2 - 1 until i - 1 by -1) { list += matrix(lowRight._1)(l) }
for (l <- lowLeft._1 - 1 until i by -1) { list += matrix(l)(lowLeft._2) } } }) list.toList } }
|