The Wayback Machine - https://web.archive.org/web/20240912164553/https://www.geeksforgeeks.org/java-program-to-rotate-matrix-elements/
Open In App

Java Program to Rotate Matrix Elements

Last Updated : 05 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 it should lookout as the matrix is rotated. Here we will be discussing two methods in dealing with indices

  1. Using naive approach 
  2. Using optimal approach 

Method 1: Using naive approach 

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

Illustrations:

For 4*4 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

Approach:

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:

  1. Move the elements of the top row,
  2. Move the elements of the last column,
  3. Move the elements of the bottom row, and
  4. Move the elements of the first column.

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

Example:

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 GFG {
    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 previous, current;
 
        // 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
            previous = matrix[rw + 1][cl];
 
            // Moving the elements of the first row
            // from rest of the rows
            for (int x = cl; x < q; x++) {
                current = matrix[rw][x];
                matrix[rw][x] = previous;
                previous = current;
            }
            rw++;
 
            // Moving the elements of the last column
            // from rest of the columns
            for (int x = rw; x < p; x++) {
                current = matrix[x][q - 1];
                matrix[x][q - 1] = previous;
                previous = current;
            }
            q--;
 
            // Moving the elements of the last row
            // from rest of the rows
            if (rw < p) {
                for (int x = q - 1; x >= cl; x--) {
                    current = matrix[p - 1][x];
                    matrix[p - 1][x] = previous;
                    previous = current;
                }
            }
            p--;
 
            // Moving elements of the first column
            // from rest of the rows
            if (cl < q) {
                for (int x = p - 1; x >= rw; x--) {
                    current = matrix[x][cl];
                    matrix[x][cl] = previous;
                    previous = current;
                }
            }
            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 

Method 2: Using optimal approach 

For a given matrix of size M×N, we need to rotate the matrix elements by k times to the right side. Where k is a number.

Approach:

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 14
         
Output : 11 12
         13 14

Example:

Java




// Java Program to Rotate Matrix to Right Side by K Times
 
// Main Class
public class GFG {
 
    // 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);
    }
}


Output

2 5 1 
4 6 3 
10 9 8 

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



Previous Article
Next Article

Similar Reads

Java Program to Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction
Given a square matrix mat[][] of dimension N and an integer K, the task is to rotate the matrix by 90 degrees K times without changing the position of the diagonal elements. Examples: Input: mat[][] = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15}, {16, 17, 18, 19, 20}, {21, 22, 23, 24, 25}}, K = 1Output: 1 16 11 6 5 22 7 12 9 2 23 18 13
4 min read
Java Program for Rotate the matrix right by K times
Given a matrix of size N*M, and a number K. We have to rotate the matrix K times to the right side. Examples: Input : N = 3, M = 3, K = 2 12 23 34 45 56 67 78 89 91 Output : 23 34 12 56 67 45 89 91 78 Input : N = 2, M = 2, K = 2 1 2 3 4 Output : 1 2 3 4 A simple yet effective approach is to consider each row of the matrix as an array and perform an
3 min read
Java Program to Rotate matrix by 45 degrees
Given a matrix mat[][] of size N*N, the task is to rotate the matrix by 45 degrees and print the matrix. Examples: Input: N = 6, mat[][] = {{3, 4, 5, 1, 5, 9, 5}, {6, 9, 8, 7, 2, 5, 2}, {1, 5, 9, 7, 5, 3, 2}, {4, 7, 8, 9, 3, 5, 2}, {4, 5, 2, 9, 5, 6, 2}, {4, 5, 7, 2, 9, 8, 3}}Output: 3 6 4 1 9 5 4 5 8 1 4 7 9 7 54 5 8 7 2 9 5 2 9 5 5 7 9 3 3 2 5 5
4 min read
Java Program for Rotate a Matrix by 180 degree
Given a square matrix, the task is that we turn it by 180 degrees in an anti-clockwise direction without using any extra space.  Examples :  Input : 1 2 3 4 5 6 7 8 9 Output : 9 8 7 6 5 4 3 2 1 Input : 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 Output : 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 Method: 1 (Only prints rotated matrix) The solution of this problem is that
6 min read
Java Program to Inplace rotate square matrix by 90 degrees | Set 1
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.Examples : Input: Matrix: 1 2 3 4 5 6 7 8 9 Output: 3 6 9 2 5 8 1 4 7 The given matrix is rotated by 90 degree in anti-clockwise direction. Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13 The given matr
5 min read
Java Program to Rotate Elements of the List
List is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. In this article, we are going to see how to rotate elements of a list. Let's consider the following list. There are two types of rotations in a list. They are right rotati
4 min read
Java Program for Program to cyclically rotate an array by one
Given an array, cyclically rotate the array clockwise by one. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: arr[] = {5, 1, 2, 3, 4}Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Java Code import java.util.Arrays; public class Test { static int arr[] = new int[]{1, 2, 3, 4, 5}; // Method for rotation static vo
1 min read
Java Program to Rotate an Image
The problem statement is to rotate an image clockwise 90 degrees for which here we will be using some in-built methods of BufferedImage class and Color c Classes required to perform the operation is as follows: To read and write an image file we have to import the File class. This class represents file and directory path names in general.To handle
3 min read
Java Program to Rotate digits of a given number by K
Given two integers N and K, the task is to rotate the digits of N by K. If K is a positive integer, left rotate its digits. Otherwise, right rotate its digits. Examples: Input: N = 12345, K = 2Output: 34512 Explanation: Left rotating N(= 12345) by K(= 2) modifies N to 34512. Therefore, the required output is 34512 Input: N = 12345, K = -3Output: 34
2 min read
Java Program to Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples:  Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6
2 min read
Java Program to Rotate the sub-list of a linked list from position M to N to the right by K places
Given a linked list and two positions 'm' and 'n'. The task is to rotate the sublist from position m to n, to the right by k places. Examples: Input: list = 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6, m = 2, n = 5, k = 2 Output: 1-&gt;4-&gt;5-&gt;2-&gt;3-&gt;6 Rotate the sublist 2 3 4 5 towards right 2 times then the modified list are: 1 4 5 2 3 6 Input: list
4 min read
Java Program to Rotate Doubly linked list by N nodes
Given a doubly linked list, rotate the linked list counter-clockwise by N nodes. Here N is a given positive integer and is smaller than the count of nodes in linked list. N = 2Rotated List: Examples: Input : a b c d e N = 2 Output : c d e a b Input : a b c d e f g h N = 4 Output : e f g h a b c d Asked in Amazon To rotate the Doubly linked list, we
4 min read
Java Program to Rotate Linked List block wise
Given a Linked List of length n and block length k rotate in a circular manner towards right/left each block by a number d. If d is positive rotate towards right else rotate towards left. Examples:  Input: 1->2->3->4->5->6->7->8->9->NULL, k = 3 d = 1 Output: 3->1->2->6->4->5->9->7->8->NULL Explanation: Here blocks of size 3 are rotated towards righ
4 min read
Java Program to Rotate bits of a number
Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. In the left rotation, the bits that fall off at the left end are put back at the right end. In the right rotation, the bits that fall off at the right end are put back at the left end. Recommen
3 min read
Java.util.Collections.rotate() Method in Java with Examples
java.util.Collections.rotate() method is present in java.util.Collections class. It is used to rotate the elements present in the specified list of Collection by a given distance. Syntax: public static void rotate(List&lt; type &gt; list, int distance) Parameters : list - the list to be rotated. distance - the distance to rotate the list. type - Ty
2 min read
How to Left or Right rotate an Array in Java?
Given an array arr[] of size N and D index, the task is to rotate the array by the D index. We have two flexibilities either to rotate them leftwards or rightwards via different ways which we are going to explore by implementing every way of rotating in both of the rotations. Ways: Using temporary arrayRecursively rotating array one by oneUsing Jug
15+ min read
Java Program to Determine if a given Matrix is a Sparse Matrix
A matrix is a collection of data elements arranged in a two-dimensional array-like structure, consisting of rows and columns. A matrix with a lot of zero values is called a sparse matrix. The program aims to count the number of zero values present in the matrix. If the number of zero values is more than half of the total number of elements in the m
3 min read
Java Program to Check Whether a Given Matrix is Lower Triangular Matrix or Not
In the lower triangular matrix, the elements that are present above the diagonal should be 0. Given a matrix and the task is to check the matrix is in lower triangular form or not. A matrix must be a square matrix. A square matrix is called lower triangular if all the entries above the main diagonal are zero. Example - Input: 1 0 0 1 2 0 1 2 3 Outp
2 min read
Java Program to Count of Array elements greater than all elements on its left and at least K elements on its right
Given an array A[ ] consisting of N distinct integers, the task is to find the number of elements which are strictly greater than all the elements preceding it and strictly greater than at least K elements on its right. Examples: Input: A[] = {2, 5, 1, 7, 3, 4, 0}, K = 3 Output: 2 Explanation: The only array elements satisfying the given conditions
7 min read
Java Program to Interchange Elements of First and Last in a Matrix Across Columns
For a given 4 x 4 matrix, the task is to interchange the elements of the first and last columns and then return the resultant matrix. Examples : Input 1 : 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2 Output 1 : 0 1 5 1 2 3 7 2 3 9 1 8 2 7 8 6 Input 2 : 7 8 9 10 11 13 14 1 15 7 12 22 11 21 30 1 Output 2 : 10 8 9 7 1 13 14 11 22 7 12 15 1 21 30 11 Approach: To ge
3 min read
Java Program to Print Boundary Elements of the Matrix
Given a matrix of size Row x Col Print the boundary elements of the matrix. Boundary elements are those elements which are not surrounded by elements on all four directions, i.e. elements in the first row, first column, last row and last column. Example: Input : 1 2 3 4 5 6 7 8 9 Output: 1 2 3 4 6 7 8 9Approach: Take the matrix as input from the us
2 min read
Java Program to Interchange Elements of First and Last in a Matrix Across Rows
For a given 4 × 4 matrix, the task is to interchange the elements of the first and last rows and then return the resultant matrix. Illustration: Input 1: 1 1 5 0 2 3 7 2 8 9 1 3 6 7 8 2 Output 1: 6 7 8 2 2 3 7 2 8 9 1 3 1 1 5 0 Input 2: 7 8 9 10 11 13 14 1 15 7 12 22 11 21 30 1 Output 2: 11 21 30 1 11 13 14 1 15 7 12 22 7 8 9 10 Approach: To get th
3 min read
Java Program to Interchange elements of first and last rows in matrix
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.Examples : Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2 Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0 Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1 Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1 The approach is very simple, we can simply swap the elements of fir
2 min read
Rotate all odd numbers right and all even numbers left in an Array of 1 to N
Given a permutation arrays A[] consisting of N numbers in range [1, N], the task is to left rotate all the even numbers and right rotate all the odd numbers of the permutation and print the updated permutation. Note: N is always even.Examples: Input: A = {1, 2, 3, 4, 5, 6, 7, 8} Output: {7, 4, 1, 6, 3, 8, 5, 2} Explanation: Even element = {2, 4, 6,
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java Program to Print Matrix in Z form
Given a square matrix of order n*n, we need to print elements of the matrix in Z form Examples: Input : mat[][] = {1, 2, 3, 4, 5, 6, 7, 8, 9} Output : 1 2 3 5 7 8 9 Input : mat[][] = {5, 19, 8, 7, 4, 1, 14, 8, 2, 20, 1, 9, 1, 2, 55, 4} Output: 5 19 8 7 14 20 1 2 55 4 Java Code // Java program to print a // square matrix in Z form import java.lang.*
2 min read
Java Program to Interchange Any Two Rows in the Matrix
Given a matrix having m rows and n columns. We have to write a Java program to interchange any two Rows in the given matrix. Swap Operation is required to interchange the elements of two rows. O(1) operation to swap two rows is impossible because complete traversal between two rows is required. Examples Input 1: K = 1, L = 2, mat[][] = {{2, 1, 4},
2 min read
Java Program to Find the Frequency of Odd &amp; Even Numbers in the Matrix
Matrix is simply a two-dimensional array. Just like in one-dimensional traversal operation is required to figure out. The task is to find the frequencies of odd and even number in the given matrix. The size of matrix is defined as product of numbers of columns and rows. So, the size of the matrix is m × n Here in the matrix M = number of rows in th
3 min read
Java Program to Find Transpose of Matrix
Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, the transpose of A[][] is obtained by changing A[i][j] to A[j][i]. Find Transpose of a Matrix in Java There are two shapes in Matrix to find transpose as mentioned below: Square MatrixRectangle Matrix1. Transpose of Square Matrix The below program fin
4 min read
Java Program to Add Two Matrix Using Iterative Approach
Given two matrices A and B, Add two matrices using iterative approaches in Java, like for loop, while loop, do-while loop. For the addition of two matrices, the necessary condition is that both the matrices must have the same size, and addition must take complete iteration to both the matrices. Examples Input: A[][] = {{1, 3}, {2, 4}} B[][] = {{1,
2 min read
Article Tags :
Practice Tags :