Lesson 2
Navigating Matrices with Zigzag Traversals in Kotlin
Introduction

Hello, fellow coder! Are you ready to tackle an exciting coding challenge using Kotlin? In this lesson, we're going to explore unique methods for traversing matrices. Matrices in Kotlin are represented as 2D arrays where each inner array maintains the same size. We'll perform a traversal through these matrices by moving up and down across columns, creating a zigzag pattern as we go. Sounds intriguing? Let's get started!

Task Statement

Here's your task: Given a 2D array where each element holds a unique integer value, your goal is to develop a function that traverses the matrix starting from the bottom-right cell. From there, you'll travel upwards to the top of the same column, then move left to the next column, and begin moving downward from the top of this new column. Continue this pattern of traversal until all cells have been visited.

Consider this small 3x4 matrix as an example:

Kotlin
1val matrix = arrayOf( 2 intArrayOf(1, 2, 3, 4), 3 intArrayOf(5, 6, 7, 8), 4 intArrayOf(9, 10, 11, 12) 5)

Using the described traversal pattern, your function should return this list: [12, 8, 4, 3, 7, 11, 10, 6, 2, 1, 5, 9].

Solution Building: Step 1

To begin our solution, we need to determine the dimensions of our matrix. We'll accomplish this using Kotlin's array properties. Let's start by setting up our function and identifying the matrix size:

Kotlin
1fun columnTraverse(matrix: Array<IntArray>): IntArray { 2 val rows = matrix.size 3 val cols = matrix[0].size 4}
Solution Building: Step 2

With the matrix dimensions known, we can set our starting point (bottom-right) and the initial direction of travel (upward). We'll also need an array to track the cells we've visited in order:

Kotlin
1fun columnTraverse(matrix: Array<IntArray>): IntArray { 2 val rows = matrix.size 3 val cols = matrix[0].size 4 var direction = "up" 5 var row = rows - 1 6 var col = cols - 1 7 val output = IntArray(rows * cols) 8 var index = 0 9}
Solution Building: Step 3

Now, let's implement a while loop to traverse the matrix. This loop will continue until all the cells have been visited. As we "visit" each cell, we'll add its value to our array.

Kotlin
1fun columnTraverse(matrix: Array<IntArray>): IntArray { 2 // Determine the number of rows and columns in the matrix 3 val rows = matrix.size 4 val cols = matrix[0].size 5 // Set initial direction of traversal to "up" 6 var direction = "up" 7 // Start from the bottom-right corner of the matrix 8 var row = rows - 1 9 var col = cols - 1 10 // Prepare an array to store the traversal result 11 val output = IntArray(rows * cols) 12 var index = 0 13 14 // Traverse until all cells have been visited 15 while (index < rows * cols) { 16 // Add the current cell's value to the output array 17 output[index++] = matrix[row][col] 18 19 // Determine the next cell based on the current direction 20 when { 21 direction == "up" -> { 22 // If moving up and reached the top, switch direction to "down" and move left 23 if (row - 1 < 0) { 24 direction = "down" 25 col -= 1 26 } else { 27 // Otherwise, move up to the previous row 28 row -= 1 29 } 30 } 31 else -> { 32 // If moving down and reached the bottom, switch direction to "up" and move left 33 if (row + 1 == rows) { 34 direction = "up" 35 col -= 1 36 } else { 37 // Otherwise, move down to the next row 38 row += 1 39 } 40 } 41 } 42 } 43 44 // Return the resulting traversal order 45 return output 46} 47 48fun main() { 49 val matrix = arrayOf( 50 intArrayOf(1, 2, 3, 4), 51 intArrayOf(5, 6, 7, 8), 52 intArrayOf(9, 10, 11, 12) 53 ) 54 55 val result = columnTraverse(matrix) 56 println(result.joinToString(" ")) 57}

And there you have it! This Kotlin function returns the output array, giving us the specific order of traversal through the matrix.

Traverse Using Decreasing Range

Let's explore another method of traversal. Kotlin allows us to use a for-loop to iterate through a 2D matrix in reverse order, utilizing ranges. This adds flexibility in creating sequences that decrement.

Consider our 3x4 matrix:

Kotlin
1val matrix = arrayOf( 2 intArrayOf(1, 2, 3, 4), 3 intArrayOf(5, 6, 7, 8), 4 intArrayOf(9, 10, 11, 12) 5)

Using a decrementing loop, the reverse traversal pattern would produce the list: [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1].

Here's how we can achieve this reverse traversal:

Kotlin
1fun reverseTraverse(matrix: Array<IntArray>): IntArray { 2 // Determine the number of rows and columns in the matrix 3 val rows = matrix.size 4 val cols = matrix[0].size 5 // Prepare an array to store the traversal result 6 val output = IntArray(rows * cols) 7 var index = 0 8 9 // Loop through rows in reverse order, starting from the last row 10 for (row in rows - 1 downTo 0) { 11 // Loop through columns in reverse order for each row 12 for (col in cols - 1 downTo 0) { 13 // Add the current cell's value to the output array 14 output[index++] = matrix[row][col] 15 } 16 } 17 18 // Return the resulting reverse traversal order 19 return output 20} 21 22fun main() { 23 val matrix = arrayOf( 24 intArrayOf(1, 2, 3, 4), 25 intArrayOf(5, 6, 7, 8), 26 intArrayOf(9, 10, 11, 12) 27 ) 28 29 val result = reverseTraverse(matrix) 30 println(result.joinToString(" ")) 31}

In this function, the loop for row starts from rows - 1 and runs to 0, decrementing at each step. Likewise, the nested loop for col starts from cols - 1 and proceeds to 0. This process allows us to begin from the bottom-right corner and traverse leftward, then upward, covering the entire matrix in reverse order.

Lesson Summary

Congratulations! You've conquered a challenging task by mastering complex matrix traversal patterns in Kotlin. The functions you've developed test not only your Kotlin coding skills but also your ability to conceptualize spatial patterns.

Now it's your turn to apply this knowledge to similar challenges. Use this lesson as your guide and don't hesitate to experiment with different matrix sizes and values. With practice, you'll soon excel at these traversal patterns! Happy coding with Kotlin!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.