Hello, fellow coder! Are you excited to dive into a new, intriguing coding challenge? In this lesson, we're going to explore special traversals of matrices. Using the Ruby programming language, we'll find our way through a matrix by climbing up and down the columns, zigzagging as we go. Sound exciting? Buckle up, then, and get ready!
Here's the task: you've been given a 2D matrix consisting of individual cells, each holding a unique integer value. Your goal is to create a function that will traverse this matrix, starting at the bottom-right cell. From there, you'll travel up to the top of the same column, move left to the next column, and continue downwards from the top of this new column. After reaching the bottom of the column, you again move left and start moving upwards. This unique traversal pattern will be performed until all the cells have been visited.
Consider this small 3 × 4 matrix as an example:
With the described traversal pattern, your function should return this list: [12, 8, 4, 3, 7, 11, 10, 6, 2, 1, 5, 9].
The first step towards a solution is understanding the dimensions of the matrix with which we're working. We can do this using Ruby's size method. Let's set up our function and identify the matrix size. Note that we assume the matrix is non-empty for this exercise:
Now that we're aware of the matrix dimensions, we should establish the starting point (bottom-right) and the direction of travel (upwards initially). Additionally, we'll need an array to keep track of the cells we've visited in order:
It's time to go exploring! We'll now implement a while loop to traverse the matrix. This loop will continue until we have covered all the cells in the matrix. As we "visit" each cell, we'll add the value in the cell to our array.
- If
direction == 'up':- Move up within the same column (
row -= 1) unless the top of the column is reached (row - 1 < 0). - Switch to 'down' and move left to the next column (
col -= 1) if the top of the column is reached.
- Move up within the same column (
- If
direction == 'down':- Move down within the same column (
row += 1) unless the bottom of the column is reached (row + 1 == rows). - Switch to 'up' and move left to the next column (
col -= 1) if the bottom of the column is reached.
- Move down within the same column (
- End the loop when all cells are visited.
- The loop continues until
output.sizematches the total number of cells (rows * cols).
That's it, we've completed the function! This Ruby function will return the output array, which gives us the order of traversal through the matrix.
