1.

Write a program in Java to print the elements of the matrix in Wave Order as shown below. (The matrix can have different numbers of rows and columns).

Answer»

It is clear from the image itself that we are traversing column-wise. Now, when we traverse an even column, we traverse it from top to bottom and when we traverse an odd column, we traverse it from bottom to top direction. 

Code for Wave Print a Matrix in Java

import java.io.*;
import java.util.*;

public class Main{

public static void main(String[] args) throws Exception {
// write your code here
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int m = scn.nextInt();

int[][] mat = new int[n][m];

//input the matrix
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
mat[i][j] = scn.nextInt();
}
}

for(int j=0;j<mat[0].length;j++) {
if(j% 2 == 0) {
for(int i=0;i<mat.length;i++) {
System.out.print(mat[i][j] + " ");
}
} else {
for(int i=mat.length-1;i>=0;i--) {
System.out.print(mat[i][j] + " ");
}
}
System.out.println();
}
}

}

Sample Output

Input:
1 2 3
4 5 6
7 8 9

Output:
1 4 7
8 5 2
3 6 9


  • Time Complexity: O(N * M) where N is the number of rows and M is the number of columns.


  • Auxiliary Space: O(1) as we have not used any extra space to solve this problem.




Discussion

No Comment Found