Traversing a 2D Matrix in C++

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 C++ 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 C++'s member functions such as size(). Let's set up our function and identify the matrix size:

C++
#include <vector>
#include <iostream>

std::vector<int> column_traverse(const std::vector<std::vector<int>>& matrix) {
    int rows = matrix.size();
    int cols = matrix[0].size();
}

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 (upward initially). Additionally, we'll need a vector to keep track of the cells we've visited in order:

C++
#include <vector>
#include <iostream>

std::vector<int> column_traverse(const std::vector<std::vector<int>>& matrix) {
    int rows = matrix.size();
    int cols = matrix[0].size();
    std::string direction = "up";
    int row = rows - 1;
    int col = cols - 1;
    std::vector<int> output;
}
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