Row Wise Traversal
Send Feedback
Code Genius is an all-in-one platform for bloggers, YouTubers, job seekers, and tech enthusiasts. It offers resources on content creation, job search, cooling pads, latest tech info, smartphones, headphones, laptops, electronics, and online earning.
Row Wise Traversal
Input :
A = [ [1, 2, 3], [4, 5, 6] ]
Output :
1 2 3 4 5 6
Explanation:
For the given matrix, the first row is [1, 2, 3], and the second is [4, 5, 6].
For row-wise traversal, you must traverse the first row and then the second.
First-line contains 'T,' denoting the number of Test cases.
For each Test case:
The first line contains two integers, ‘N' and ‘M’.
The following ‘N’ lines have ‘M’ integers each, denoting the matrix ‘A’.
You must return the array with elements in order of row-wise traversal.
You don’t need to print anything. Just implement the given function.
1 <= T <= 10
1 <= N * M <= 10^5
1 <= A[ i ][ j ] <= 10^9
Time Limit: 1 sec
2
2 2
4 3
2 1
1 5
1 2 3 4 5
4 3 2 1
1 2 3 4 5
For test case one:
Input :
A = [ [4, 3], [2, 1] ]
Output :
4 3 2 1
Explanation: For the given matrix, the first row is [4, 3], and the second is [2, 1].
For row-wise traversal, you must traverse the first row and then the second.
For test case two:
Input :
A = [ [1, 2, 3, 4, 5] ]
Output :
1 2 3 4 5
Explanation: For the given matrix, the first row is [1, 2, 3, 4, 5].
For row-wise traversal, you need to traverse the first row.
2
1 1
4
5 1
1
2
3
4
5
4
1 2 3 4 5
code for this
public class Solution { public static int[] printRowWise(int[][] a) { int numRows = a.length; int numCols = a[0].length; int[] result = new int[numRows * numCols]; int index = 0;
for (int i = 0; i < numRows; i++) { for (int j = 0; j < numCols; j++) { result[index++] = a[i][j]; } }
return result; }
public static void main(String[] args) { // Sample input int[][] matrix1 = {{4, 3}, {2, 1}}; int[][] matrix2 = {{1, 2, 3, 4, 5}};
// Call the printRowWise function for each test case int[] result1 = printRowWise(matrix1); int[] result2 = printRowWise(matrix2);
// Print the results for (int num : result1) { System.out.print(num + " "); } System.out.println();
for (int num : result2) { System.out.print(num + " "); } }}
Comments
Post a Comment