Print Matrix in snake Pattern in java

Print Matrix in snake Pattern in java

Given a matrix of size N x N. Print the elements of the matrix in the snake like pattern depicted below.

Your task is to complete the function printSnakePattern which receives the input matrix and N as its parameters and prints the matrix in snake pattern.

Input Format

  • The first line contains an integer N.
  • The next N lines contains N spaced integers each, elements of matrix.

Output Format

Print the elements of the matrix in the snake like pattern.

Example 1

Input

3 
45 48 54
21 89 87
70 78 15

Output

45 48 54 87 89 21 70 78 15

Example 2

Input

2 
1 2
3 4

Output

1 2 4 3

Constraints

  • 1 <= N <= 100
  • 1 <= mat[i][j] <= 100

Solution of Print Matrix in snake Pattern in java:–

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

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int [][]arr = new int[n][n];

      for(int i=0;i<n;i++)
        {
          for(int j=0;j<n;j++)
            {
              arr[i][j]=sc.nextInt();
            }
        }

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

Add a Comment

Your email address will not be published. Required fields are marked *