Rotate Matrix clockwise Java
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void rotate(int m,int n,int arr[][])
{
int row=0,col=0;
int m1=m,n1=n;
int curr,prev;
while(row<n && col<m)
{
if (row + 1 == m || col + 1 == n)
break;
prev=arr[row+1][col];
for(int i=col;i<n;i++)
{
curr=arr[row][i];
arr[row][i]=prev;
prev=curr;
}
row++;
for(int i=row;i<m;i++)
{
curr=arr[i][n-1];
arr[i][n-1]=prev;
prev=curr;
}
n--;
if(row<m)
for(int i=n-1;i>=col;i--)
{
curr = arr[m-1][i];
arr[m-1][i] = prev;
prev = curr;
}
m--;
/* Move elements of first column from the remaining rows */
if (col < n)
{
for (int i = m-1; i >= row; i--)
{
curr = arr[i][col];
arr[i][col] = prev;
prev = curr;
}
}
col++;
}
for(int i=0;i<m1;i++)
for(int j=0;j<n1;j++)
System.out.print(arr[i][j]+" ");
System.out.println();
}
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
int m=ab.nextInt();
int arr[][]=new int[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
arr[i][j]=ab.nextInt();
rotate(n,m,arr);
}
}
}
import java.lang.*;
import java.io.*;
class GFG
{
public static void rotate(int m,int n,int arr[][])
{
int row=0,col=0;
int m1=m,n1=n;
int curr,prev;
while(row<n && col<m)
{
if (row + 1 == m || col + 1 == n)
break;
prev=arr[row+1][col];
for(int i=col;i<n;i++)
{
curr=arr[row][i];
arr[row][i]=prev;
prev=curr;
}
row++;
for(int i=row;i<m;i++)
{
curr=arr[i][n-1];
arr[i][n-1]=prev;
prev=curr;
}
n--;
if(row<m)
for(int i=n-1;i>=col;i--)
{
curr = arr[m-1][i];
arr[m-1][i] = prev;
prev = curr;
}
m--;
/* Move elements of first column from the remaining rows */
if (col < n)
{
for (int i = m-1; i >= row; i--)
{
curr = arr[i][col];
arr[i][col] = prev;
prev = curr;
}
}
col++;
}
for(int i=0;i<m1;i++)
for(int j=0;j<n1;j++)
System.out.print(arr[i][j]+" ");
System.out.println();
}
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
int n=ab.nextInt();
int m=ab.nextInt();
int arr[][]=new int[n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
arr[i][j]=ab.nextInt();
rotate(n,m,arr);
}
}
}
0 Comments:
Post a Comment