Given a square matrix, turn it by 90 degrees in clockwise direction without using any extra space.
Input: 1 2 3 4 5 6 7 8 9 Output: 7 4 1 8 5 2 9 6 3 Input: 1 2 3 4 Output: 3 1 4 2
Approach: The approach is similar to Inplace rotate square matrix by 90 degrees | Set 1. The only thing that is different is to print the elements of cycle in clockwise direction i.e. An N x N matrix will have floor(N/2) square cycles.
For example, a 3 X 3 matrix will have 1 cycle. The cycle is formed by its 1st row, last column, last row, and 1st column.
For each square cycle, we swap the elements involved with the corresponding cell in the matrix in the clockwise direction. We just need a temporary variable for this.
Let size of row and column be 3.
During first iteration –
a[i][j] = Element at first index (leftmost corner top)= 1.
a[j][n-1-i]= Rightmost corner top Element = 3.
a[n-1-i][n-1-j] = Righmost corner bottom element = 9.
a[n-1-j][i] = Leftmost corner bottom element = 7.
Move these elements in the clockwise direction.
During second iteration –
a[i][j] = 2.
a[j][n-1-j] = 6.
a[n-1-i][n-1-j] = 8.
a[n-1-j][i] = 4.
Similarly, move these elements in the clockwise direction.
Below is the implementation of above approach:
13 9 5 1 14 10 6 2 15 11 7 3 16 12 8 4
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Rotate a matrix by 90 degree without using any extra space | Set 2
- Rotate a Matrix by 180 degree
- Print n x n spiral matrix using O(1) extra space
- Element in a matrix starting from which anti-clockwise traversal ends at the last element
- Print a given matrix in spiral form using direction tracking method
- Move matrix elements in given direction and add elements with same value
- Final direction after visiting every cell of Matrix starting from (0, 0)
- Clockwise rotation of Linked List
- Check if a string can be formed from another string by at most X circular clockwise shifts
- Rotate Matrix Elements
- Inplace rotate square matrix by 90 degrees | Set 1
- Rotate each ring of matrix anticlockwise by K elements
- Rotate the matrix right by K times
- Rotate matrix by 45 degrees
- Turn an image by 90 degree
- Maximum trace possible for any sub-matrix of the given matrix
- Direction at last square block
- Count possible moves in the given direction in a grid
- Rotate bits of a number
- Program to cyclically rotate an array by one
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.