object PrintMatrixInSpiralForm_Scala {
def printMatrixInSpiralForm(matrix: Array[Array[Int]]): Unit = {
if (matrix == null || matrix.length == 0) return
var top = 0
var bottom = matrix.length - 1
var left = 0
var right = matrix(0).length - 1
while (true) {
if (left > right) return
// top row
for (i <- left to right) {
print(s"${matrix(top)(i)} ")
}
println()
top += 1 // next row
if (top > bottom) return
// right column
for (i <- top to bottom) {
print(s"${matrix(i)(right)} ")
}
println()
right -= 1 // previous column
if (left > right) return
// bottom row
for (i <- right to left by -1) {
print(s"${matrix(bottom)(i)} ")
}
println()
bottom -= 1 // previous row
if (top > bottom) return
// left column
for (i <- bottom to top by -1) {
print(s"${matrix(left)(i)} ")
}
println()
left += 1 // next column
}
}
def main(args: Array[String]): Unit = {
val matrix = Array(
Array( 1, 2, 3, 4),
Array( 5, 6, 7, 8),
Array( 9, 10, 11, 12),
Array(13, 14, 15, 16)
)
printMatrixInSpiralForm(matrix)
}
}
/*
run:
1 2 3 4
8 12 16
15 14 13
9 5
6 7
11
10
*/