VOOZH about

URL: https://www.geeksforgeeks.org/java/java-program-to-rotate-matrix-elements/

⇱ Java Program to Rotate Matrix Elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Program to Rotate Matrix Elements

Last Updated : 1 May, 2025

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:

  • Move the elements of the top row,
  • Move the elements of the last column,
  • Move the elements of the bottom row, and
  • Move the elements of the first column.

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

Illustration:


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 14 Output: 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.


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.

Comment
Article Tags: