Printing Elements of a 2D array in Zig-Zag
Description
Given a matrix with n rows and m columns. Print the matrix elements starting from the top right corner and follow a zig-zag pattern.
Look at the image for better understanding
Input
Input Format
First line contains n and m
Next n line contains m space separated integers which describe each row of the 2d array
Constraints
n,m <=50
Output
Print all matrix elements in a single line separated by spaces.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
int [][]arr = new int[row][col];
for (int i =0;i<row;i++){
for (int j = 0 ; j<col;j++){
arr[i][j]=sc.nextInt();
}
}
for (int i =0;i<row;i++){
for (int j = 0 ; j<col;j++){
if (i%2==0){
System.out.print(arr[i][col-1-j]+" ");
}else {
System.out.print(arr[i][j]+" ");
}
}
System.out.println();
}
}
}
No comments:
Post a Comment