Given a matrix with N rows and M columns, print all elements row by row from left to right.
Example 1
Input: mat = [[1, 2, 3], [4, 5, 6]]
Output: 1 2 3 4 5 6
Explanation: First row prints as 1 2 3, then second row prints as 4 5 6.
Example 2
Input: mat = [[10, 20], [30, 40], [50, 60]]
Output: 10 20 30 40 50 60
Explanation: Traversal prints each row from left to right before moving downward to the next row.
Approach
This approach prints the matrix one row at a time. The outer loop selects each row, while the inner loop traverses all columns in that row from left to right. Every element is printed as soon as it is visited, so no extra space is required.
Algorithm
Find the number of rows and columns in the matrix, as these define the limits of our traversal.
For row-wise traversal, use an outer loop to access each row one by one.
Use an inner loop for the columns, which makes sure every element within the current row is accessed from left to right.
Print the current element as soon as it is accessed, since we want the elements in the same order as they appear in each row.
Continue until all rows and their corresponding columns have been processed.
Dry Run
print row wise
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: // Function to print matrix elements row by row. void printRowWise(vector<vector<int>>& mat) { // Store total number of rows. int n = mat.size(); // Handle an empty matrix. if (n == 0) { cout << "\n"; return; } // Store total number of columns. int m = mat[0].size(); // Track first printed value for spacing. bool first = true; // Traverse every row from top to bottom. for (int row = 0; row < n; row++) { // Traverse every column from left to right. for (int col = 0; col < m; col++) { // Print a space before every value except the first. if (!first) { cout << " "; } // Print the current matrix element. cout << mat[row][col]; // Mark first value as printed. first = false; } } // Move to the next line after printing finishes. cout << "\n"; }};// Driver code.int main() { vector<vector<int>> mat = {{1, 2, 3}, {4, 5, 6}}; Solution sol; sol.printRowWise(mat); return 0;}Complexity Analysis
Time Complexity: O(N × M), traversal visits every matrix cell exactly once.
Space Complexity: O(1), only loop variables are used apart from output handling.
Interview follow-up Questions
Yes. One loop selects each row, and another loop scans each column inside the selected row.
Be the first to add a comment.