You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
Input Format You will take 2 integers n m denoting the size of the 2D matrix Next you will take input in form of a matrix in taking n rows, m columns and input will be rowwise.
Output Format Output shouls be a matrix that is rotate by 90 degrees in the clockwise direction.
Examples:
Input :
2 2 1 2 2 3
Output:
2 1 3 2
Input :
3 3 7 2 3 2 3 4 5 6 1
Output :
5 2 7 6 3 2 1 4 3
Solution of Rotate a matrix by 90 degrees :–
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(); } } //transpose array for(int i=0;i<arr.length;i++) { for(int j=i+1;j<arr[i].length;j++) { int temp=arr[i][j]; arr[i][j]=arr[j][i]; arr[j][i]=temp; } } //reverse an array for(int i=0;i<n;i++) { int start=0; int end=n-1; while(start<end) { int temp=arr[i][start]; arr[i][start]=arr[i][end]; arr[i][end]=temp; start++; end--; } } //printing matrix for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[i].length;j++) { System.out.print(arr[i][j]+" "); } System.out.println(); } } }
Add a Comment