# Rotate Matrix By 90 Degree

### 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:
1. First check matrix is square or not
1. Iterate layer from 0 to n/2
1. Set FirstCell = rotation
2. Set LastCell = n – layer – 1
3. Iterate cell from FirstCell to LastCell
1. Set offset = i – FirstCell
2. Set topLeftValue = matrix[FirstCell][i]
3. Set matrix[FirstCell][i] = matrix [last-offset][FirstCell]
4. Set matrix [LastCell – offset][FirstCell] = matrix [last-offset] [LastCell]
5. Set matrix [LastCell – offset][LastCell] = matrix [i][LastCell]
6. Set matrix [i][LastCell] = topLeftValue

Latest Source Code:
Github: RotateMatrixBy90Degree.java

Output:

```7 4 1
8 5 2
9 6 3
```
Author: