Introduction

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 Python 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!

Task Statement
Solution Building: Step 1

The first step towards a solution is understanding the dimensions of the matrix with which we're working. We can do this using Python's built-in len() function. Let's set up our function and identify the matrix size:

def column_traverse(matrix):
    rows = len(matrix)
    cols = len(matrix[0])
Solution Building: Step 2

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 a list to keep track of the cells we've visited in order:

def column_traverse(matrix):
    rows, cols = len(matrix), len(matrix[0])
    direction = 'up'
    row, col = rows - 1, cols - 1
    output = []
Solution Building: Step 3

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 list.

def column_traverse(matrix):
    rows, cols = len(matrix), len(matrix[0])
    direction = 'up'
    row, col = rows - 1, cols - 1
    output = []
    
    while len(output) < rows * cols:
        output.append(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

    return output

That's it, we've completed the function! This Python function will return the output list, which gives us the order of traversal 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