VOOZH about

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

⇱ C Program to Rotate Matrix Elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C Program to Rotate Matrix Elements

Last Updated : 26 Jul, 2022

Here, we will build a C Program to rotate matrix elements with an approach to ring/rotate elements independently.

Input:

1 2 3
4 5 6
7 8 9

Output:

4 1 2 
7 5 3
8 9 6

Approach 

We rotate all rings of elements one by one, This process is starting from the outermost ring, and then follows the same step for the inner ring. To rotate a ring, we need to do the following steps. 

  1. Move elements of the top row
  2. Move elements of the last column
  3. Move elements of the bottom row
  4. Move elements of the first column
  5. Repeat the above steps for the inner ring while there is an inner ring.

Example:


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

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

Time Complexity: O(m*n), where m is the number of rows and n is the number of columns.
Auxiliary Space: O(1), No extra Space is used.

Comment
Article Tags: