Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Semrush - keyword research tool

Linux Foundation Training and Certification

Teach Your Child To Read

Disclosure: My content contains affiliate links.

32,304 questions

42,479 answers

573 users

How to print a given matrix in spiral form with Scala

1 Answer

0 votes
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 
     
*/

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered Sep 3 by avibootz
edited Sep 3 by avibootz

Related questions

1 answer 10 views
1 answer 11 views
1 answer 56 views
1 answer 53 views
1 answer 65 views
...