Java Program to Rotate Matrix Elements (original) (raw)

Last Updated : 01 May, 2025

Try it on GfG Practice redirect icon

A matrix is simply a two-dimensional array. So, the goal is to deal with fixed indices at which elements are present and to perform operations on indexes such that elements on the addressed should be swapped in such a manner that it should look out as the matrix is rotated.

For a given matrix, the task is to **rotate its elements in a clockwise direction.

**Example of Elements Rotation in a Matrix

**For 3*3 matrix

**Input:
7 8 9
10 11 12
2 3 4

**Output:
10 7 8
2 11 9
3 4 12

**For 4*4 matrix

**Input:
4 5 6 7
8 9 10 11
12 13 14 15
16 17 18 19

**Output:
8 4 5 6
12 13 9 7
16 14 10 11
17 18 19 15

**Program to Rotate Matrix Elements in Java

Here, we will use loops in order to print the elements in spiral form. Where, we will rotate all the rings of the elements one by one, starting from the outermost one. And for rotating a ring, we need to do the following:

Repeat the above steps, if there is an inner ring as well.

**Illustration:

Java `

// Java Program to Rotate Matrix Elements

// Importing classes from java.lang package import java.lang.*;

// Importing classes from java.util package import java.util.*;

// main Class class Geeks { static int r = 4; static int c = 4;

// Method  
// To rotate a matrix of
// dimension r x c. And initially,
// p = r and q = c
static void rotate_matrix(int p, int q, int matrix[][])
{
    int rw = 0, cl = 0;
    int prev, cur;

    // rw is the Starting row index
    // p is the ending row index
    // cl is the starting column index
    // q is the ending column index and
    // x is the iterator
    while (rw < p && cl < q) {

        if (rw + 1 == p || cl + 1 == q)
            break;

        // After storing the first element of the
        // next row, this element will substitute
        // the first element of the current row
        prev = matrix[rw + 1][cl];

        // Moving the elements of the first row
        // from rest of the rows
        for (int x = cl; x < q; x++) {
            cur = matrix[rw][x];
            matrix[rw][x] = prev;
            prev = cur;
        }
        rw++;

        // Moving the elements of the last column
        // from rest of the columns
        for (int x = rw; x < p; x++) {
            cur = matrix[x][q - 1];
            matrix[x][q - 1] = prev;
            prev = cur;
        }
        q--;

        // Moving the elements of the last row
        // from rest of the rows
        if (rw < p) {
            for (int x = q - 1; x >= cl; x--) {
                cur = matrix[p - 1][x];
                matrix[p - 1][x] = prev;
                prev = cur;
            }
        }
        p--;

        // Moving elements of the first column
        // from rest of the rows
        if (cl < q) {
            for (int x = p - 1; x >= rw; x--) {
                cur = matrix[x][cl];
                matrix[x][cl] = prev;
                prev = cur;
            }
        }
        cl++;
    }

    // Prints the rotated matrix
    for (int x = 0; x < r; x++) {
        for (int y = 0; y < c; y++)
            System.out.print(matrix[x][y] + " ");
        System.out.print("\n");
    }
}

// Method 2
// Main driver method
public static void main(String[] args)
{

    // Custom input array
    int b[][] = { { 5, 6, 7, 8 },
                  { 1, 2, 3, 4 },
                  { 0, 15, 6, 5 },
                  { 3, 1, 2, 12 } };

    // Calling function(Method1) to rotate matrix
    rotate_matrix(r, c, b);
}

}

`

Output

1 5 6 7 0 15 2 8 3 6 3 4 1 2 12 5

Optimal Approach to Rotate Matrix Elements

An optimal approach is to observe each row of the stated matrix as an array and then execute an array rotation. It is performed by replicating the elements of the matrix from the given number _k to the end of an array to the starting of the array utilizing a temporary array. And then the rest of the elements from the start to (__k_-1) to the end of an array.

**Illustration:

Input: M = 3, N = 3, k = 2 1 2 3 4 5 6 7 8 9 Output: 2 3 1 5 6 4 8 9 7 Input: M = 2, N = 2, k = 2 11 12 13 14Output: 11 12 13 14

**Example: For a given matrix of size **P×Q, we need to rotate its elements layer-wise in a clockwise direction by **K times to the right side, where **K is a given number.

Java `

// Java Program to Rotate Matrix to Right Side by K Times

// Main Class public class Geeks { // Dimension of the matrix

// Initializing to custom values
static final int P = 3;
static final int Q = 3;

// Method 1
// To rotate the stated matrix by K times
static void rotate_Matrix(int mat[][], int K)
{
    // Using temporary array of dimension P
    int tempo[] = new int[P];

    // Rotating matrix by k times 
    // across the size of matrix
    K = K % P;

    for (int j = 0; j < Q; j++) {

        // Copying first P-K elements
        // to the temporary array
        for (int l = 0; l < P - K; l++)
            tempo[l] = mat[j][l];

        // Copying the elements of the matrix
        // from K to the end to the starting
        for (int x = P - K; x < P; x++)
            mat[j][x - P + K] = mat[j][x];

        // Copying the elements of the matrix
        // from the temporary array to end
        for (int x = K; x < P; x++)
            mat[j][x] = tempo[x - K];
    }
}

// Method 2
// To show the resultant matrix
static void show_Matrix(int mat[][])
{
    for (int j = 0; j < Q; j++) {
        for (int x = 0; x < P; x++)
            System.out.print(mat[j][x] + " ");
        System.out.println();
    }
}

// Method 3
// Main driver method
public static void main(String[] args)
{
    // Custom input array
    int mat[][]
        = { { 1, 2, 5 }, { 3, 4, 6 }, { 8, 10, 9 } };

    // Custom value of K
    int K = 2;

    // Calling the above created method for
    // rotating matrix by k times
    rotate_Matrix(mat, K);

    // Calling the above method for
    // displaying rotated matrix
    show_Matrix(mat);
}

}

`

**Time complexity: O(R*C) where, R and **C are no of rows and columns of given matrix respectively.
**Auxiliary space: O(1), because using array tempo of size 3.