![]() |
VOOZH | about |
Given a square matrix, the task is to rotate its elements counterclockwise by one step.
Examples:
Input
1 2 3
4 5 6
7 8 9
Output:
2 3 6
1 5 9
4 7 8Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
2 3 4 8
1 7 11 12
5 6 10 16
9 13 14 15
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 back (except the first element)
b) Move the rightmost column elements one position up (except the first element)
c) Move the bottom row elements one position right (Except the rightmost element)
d) Move the first column elements one position down (Except the bottom elements)
2. Repeat the same process for inner layers.
2 3 4 8 1 7 11 12 5 6 10 16 9 13 14 15
Time Complexity: O(m*n) where m is the number of rows & n is the number of columns.
Auxiliary Space: O(1).