Rotate Matrix By 90 Degree
Rotate given matrix by 90 degree but rotation must be in place rotation
Conditions:
- In place rotation
- 2 D matrix
- And clockwise rotation
Solution:
- We’ll rotate layer by layer
- Total number layer required to rotate = n / 2
- We will swap following cells values for every layer rotation:
- TopLeft -> TopRight
- TopRight – BottomRight
- BottomRight -> BottomLeft
- BottomLeft -> TopRight
- Cells
- TopLeft = layer, layer
- TopRight = n – layer – 1, layer
- BottomLeft = layer, n – layer – 1
- BottomRight = n – layer – 1, n – layer – 1
Algorithm:
- First check matrix is square or not
- Iterate layer from 0 to n/2
- Set FirstCell = rotation
- Set LastCell = n – layer – 1
- Iterate cell from FirstCell to LastCell
- Set offset = i – FirstCell
- Set topLeftValue = matrix[FirstCell][i]
- Set matrix[FirstCell][i] = matrix [last-offset][FirstCell]
- Set matrix [LastCell – offset][FirstCell] = matrix [last-offset] [LastCell]
- Set matrix [LastCell – offset][LastCell] = matrix [i][LastCell]
- Set matrix [i][LastCell] = topLeftValue
- Iterate layer from 0 to n/2
Latest Source Code:
Github: RotateMatrixBy90Degree.java
Output:
7 4 1 8 5 2 9 6 3