Rotate Image(N * N Array) [codingblocks]

Given a 2D array of size N x N. Rotate the array 90 degrees anti-clockwise.


Input Format
First line contains a single integer N. Next N lines contain N space separated integers.

Constraints
N < 1000

Output Format
Print N lines with N space separated integers of the rotated array.

Sample Input
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Sample Output
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13

Explanation
Rotate the array 90 degrees anticlockwise.



Java Code:



/*
Amit Kumar
06-12-2020
IDE Code: https://ide.geeksforgeeks.org/jMPFThJmNz
*/

package array;
import java.util.Scanner;

public class Array_RotateImage {
    public static Scanner scanner = new Scanner(System.in);
    public static void main(String[] args) {
        int size = scanner.nextInt();
        int [][] matrix = new int[size][size];
        for (int i=0;i <size; i++) {
            for (int j=0; j <size; j++) {
                matrix[i][j] = scanner.nextInt();
            }
        }
        rotate90DegreeAntiClockwise(matrix, size);

        for (int i=0;i <size; i++) {
            for (int j=0; j <size; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println("");
        }
    }

    private static void rotate90DegreeAntiClockwise(int[][] mat, int no) {
        for(int i=0;i<no/2;i++)
        {
            for(int j=i;j<no-i-1;j++)
            {
                int temp=mat[i][j] ;
                mat[i][j]=mat[j][no-i-1] ;
                mat[j][no-i-1]=mat[no-i-1][no-j-1] ;
                mat[no-i-1][no-j-1]=mat[no-j-1][i] ;
                mat[no-j-1][i]=temp ;
            }
        }
    }
}

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )