Alternate Manner Matrix Traversal in java

Alternate Manner Matrix Traversal in java

Given a 2D array, the task is to print the 2D in alternate manner (First row from left to right, then from right to left, and so on). Examples:

Input : arr[][2] = [[1, 2], [2, 3]]; Output : 1 2 3 2

Input :arr[][3] = [[ 7 , 2 , 3 ], [ 2 , 3 , 4 ], [ 5 , 6 , 1 ]]; Output : 7 2 3 4 3 2 5 6

Solution of Alternate Manner Matrix Traversal :–

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 m = sc.nextInt();

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

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

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

Add a Comment

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