Introduction

Greetings, aspiring Scala programmer! Are you eager to delve into the captivating challenge of matrix traversal in Scala? In this lesson, we’ll explore unique traversal patterns of matrices using the expressive and type-safe Scala language. Our journey will navigate through a matrix in a zigzag pattern, moving up and down the columns. Prepare yourself for an exciting journey as we unravel the depths of matrix manipulation in Scala!

Task Statement
Solution Building: Step 1

To begin, we must understand the dimensions of the matrix we're working with. We'll use Scala's array properties to determine this aspect. Let's initiate our function and ascertain the matrix size:

def columnTraverse(matrix: Array[Array[Int]]): List[Int] = {
  val rows = matrix.length
  val cols = matrix(0).length
}
Solution Building: Step 2

Having established the matrix dimensions, it’s important to set our initial position (bottom-right) and direction (upward to start). Additionally, we'll need a structure to log the cells visited:

def columnTraverse(matrix: Array[Array[Int]]): List[Int] = {
    val rows = matrix.length
    val cols = matrix(0).length
    var direction = "up"
    var row = rows - 1
    var col = cols - 1
    var output: List[Int] = List()
}
Solution Building: Step 3

Let's embark on our exploration! We'll use a while loop to handle the matrix traversal. The loop continues until all cells in the matrix have been visited. The value at each visited cell is appended to our list as follows:

def columnTraverse(matrix: Array[Array[Int]]): List[Int] = {
  val rows = matrix.length
  val cols = matrix(0).length
  var direction = "up"
  var row = rows - 1
  var col = cols - 1
  var output: List[Int] = List()
  
  while (output.length < rows * cols) {
    output = output :+ matrix(row)(col)
    
    if (direction == "up") {
      if (row - 1 < 0) {
        direction = "down"
        col -= 1
      } else {
        row -= 1
      }
    } else {
      if (row + 1 == rows) {
        direction = "up"
        col -= 1
      } else {
        row += 1
      }
    }
  }
  
  output
}

Congratulations, our function is complete! This Scala function will now return the output list, presenting the traverse order through the matrix.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal