A matrix is just a table of numbers. It has rows (going across, left to right) and columns (going down, top to bottom). In code, we often store a matrix as a list of lists, where each inner list is one row.
For example:
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
This matrix has 3 rows and 3 columns.
To traverse a matrix means to visit every single number in it, one by one, in some order. The order we pick has a name. Here we use row-major order.
In row-major order, we read the numbers one full row at a time, from top to bottom. Think of it exactly like reading a page in a book: you read the first line completely from left to right, then drop down to the next line and read it completely, and so on.
So for the matrix above, we read:
1, 2, 34, 5, 67, 8, 9Joined together, the output is:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
The key idea to remember: *the consecutive elements of a single row sit next to each other in the result.* We finish a whole row before moving to the next one.
Rows do not have to be the same length as the number of rows. Take this matrix with 2 rows and 4 columns:
matrix = [[3, 2, 1, 7],
[0, 6, 3, 2]]
Read the first row fully (3, 2, 1, 7), then the second row fully (0, 6, 3, 2). The output is:
[3, 2, 1, 7, 0, 6, 3, 2]
The natural way is to use two loops, one inside the other:
0 and going down to the last row.In C++ the function header looks like this:
class Solution {
public:
vector<int> rowMajorTraversal(vector<vector<int>>& matrix) {
}
};
Here matrix[i][j] means: the number at row i and column j. The outer loop changes i (which row), and the inner loop changes j (which column). You append matrix[i][j] to your answer each time, and when both loops finish, you return the answer.
The result simply follows the reading order: across each row, then down to the next.