A matrix is just a table of numbers arranged in rows and columns. Think of it like a chessboard or a spreadsheet, where every box holds one value. To work with a matrix, we often need to visit every box one by one. The order in which we visit them is called a traversal.
There are two common ways to walk through a matrix. The usual way is row by row — finish the whole first row, then the second row, and so on. But here we learn a different order: column-major traversal, where we go column by column instead.
In column-major order, we visit all the numbers in the first column from top to bottom, then move to the second column and read it top to bottom, and keep going until every column is done. In simple words: the numbers of one full column stay together, one after another, before we touch the next column.
Take this matrix:
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Here the columns are:
1, 4, 7 (top to bottom).2, 5, 8.3, 6, 9.So we read column 0 first → 1, 4, 7, then column 1 → 2, 5, 8, then column 2 → 3, 6, 9. Joining them gives the answer:
Output: [1, 4, 7, 2, 5, 8, 3, 6, 9]
Notice how 1, 4, 7 are the top, middle, and bottom of the same column. That is the key idea — we move down a column before moving right to the next one.
To pick a value we use two index numbers: a row index and a column index, written as matrix[row][col]. In a normal row-major walk, the outer loop runs over rows and the inner loop over columns. For column-major, we simply swap that order:
0.matrix[row][col] from top to bottom.In C++ this fits a function like:
vector<int> columnMajorTraversal(vector<vector<int>> matrix)
It takes the matrix and returns a list (vector<int>) holding the numbers in column-major order.
For matrix = [[3, 2, 1, 7], [0, 6, 3, 2]], there are 2 rows and 4 columns. Reading each column top to bottom gives: column 0 → 3, 0; column 1 → 2, 6; column 2 → 1, 3; column 3 → 7, 2. So the traversal is [3, 0, 2, 6, 1, 3, 7, 2].
The single thing to remember: down a column first, then across to the next column.