Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, September 26, 2018

Rotate Matrix represented in 1D inplace


Problem:
1-D array contained N*N elements. Assuming that the N*N elements form a matrix, you have to rotate the matrix in-place

Prerequisites :
Rotate matrix represented in N*N

Idea is to find transpose of the matrix
Then reverse every n blocks to rotate right 
OR for left rotate
Reverse whole matrix and rightRotate It.
Formula to find a[i][j]
a[col*i+j]


Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class rotatematrix1d
 {
   public static void reverse(int a[],int start,int end)
   {
     while(start<end)
     {
       int temp=a[start];
       a[start]=a[end];
       a[end]=temp;
       ++start;
       --end;
     }
   }
   public static void transpose(int a[],int n)
   {
     for(int i=0;i<n;++i)
     {
       for(int j=i;j<n;++j)
       {
         int temp=a[n*i+j];
         a[n*i+j]=a[n*j+i];
         a[n*j+i]=temp;
       }
     }

     for(int x:a)
     System.out.print(x+" ");

     System.out.println();
   }
   public static void rightRotate(int a[],int n)
   {
     int i=n;
     while(i<=n*n)
     {reverse(a,i-n,i-1);
     i+=n;}
   }
   public static void leftRotate(int a[],int n)
   {
     reverse(a,0,n*n-1);

     rightRotate(a,n);
   }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
    int n=ab.nextInt();
    int arr[]=new int[n*n];
    for(int i=0;i<n*n;++i)
    arr[i]=ab.nextInt();
      transpose(arr,n);
      //rightRotate(arr,n);
      leftRotate(arr,n);
      for(int x:arr)
      System.out.print(x+" ");
    System.out.println();

}
}

0 Comments:

Post a Comment

Stats