VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rotate-matrix-elements/

⇱ Rotate Matrix Clockwise by 1 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rotate Matrix Clockwise by 1

Last Updated : 17 Oct, 2024

Given a square matrix, the task is to rotate its elements clockwise by one step.

Examples:

Input
1 2 3
4 5 6
7 8 9
Output:
4 1 2
7 5 3
8 9 6

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

The idea is to use nested loops to move elements in four directions (right, down, left, and up) one step at a time for each layer starting from the outermost layer. This simulates the clockwise rotation by rotating each "ring" or layer of the matrix.

1. First move the elements of the outermost layer.
a) Move the top row elements one position ahead (except the last element)
b) Move the rightmost column elements one position down (except the last element)
c) Move the bottom row elements one position left (Except the leftmost element)
d) Move the first column elements one position up (Except the top elements)

2. Repeat the same process for inner layers.


Output
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 & n is the number of columns.
Auxiliary Space: O(1). 

Comment
Article Tags: