Explore
ProGrad Programs
Placement Prep
TCS Codevita
Webinars
About Us

Edit
Reply




Edit

Rotate the matrix by K times | Program in C++, java, Python

Published on 06 Mar 2020

Rotate the matrix by K times means rotating the given N*N matrix to the specified (K) number of times. For example, consider the 3*3 matrix, which has to be rotated once,


Matrix before Rotation :

10  20  30                                 

40  50  60          

70  80  90                            

 

Matrix after rotation : 

20  30  10

50  60  40

80  90  70

 

Steps:

  • Consider the matrix as 3 rows. Each element in the row is rotated to its right once.
  • One efficient method is to consider each matrix row as an array and perform array rotation.
  • Copy the elements from K to end of array in a temporary array and then temporary array is made as the start of the array. 
  • And then the remaining elements from start to K-1 are copied in temporary array and then set to the end of the array.
  • Thus, the matrix gets shifted.

 

C++
Java
Python 3

Output
Enter the matrix elements
1 2 3 4 5 6 7 8 9
The given matrix is
1 2 3
4 5 6
7 8 9
Number of rotations: 2

The rotated matrix is
2 3 1
5 6 4
8 9 7

If you have any feedback about this article and want to improve this, please write to enquiry@faceprep.in
Explore 'c plus plus'
Articles Practice Exercises