Explanation :

First Cycle (Involves bold elements)

**5 1 9 11**

**2** 4 8 **10**

**13** 3 6 **7**

**15 14 12 16**

Moving first group of four elements (First

elements of 1st row, last row, 1st column

and last column) of first cycle in

clockwise.

**15** 1 9 **5**

2 4 8 10

13 3 6 7

**16** 14 12 **11**

Moving next group of four elements of

first cycle in counter clockwise

15 **13** 9 5

2 4 8 **1**

**12** 3 6 7

16 14 **10** 11

Moving final group of four elements of

first cycle in counter clockwise

15 13 **2** 5

**14** 4 8 1

12 3 6 **9**

16 **7** 10 11

Second Cycle (Involves Bold Elements)

15 13 2 5

14 **4** **8** 1

12 **3** **6** 9

16 7 10 11

Fixing second cycle

15 13 2 5

14 **3** **4** 1

12 **6** **8** 9

16 7 10 11

Code : Outer loop = For cycles, Inner loop = Moving elements in group of four for the cycle specified by outer loop

```
public void rotate(int[][] mat) {
int n = mat.length;
for (int k = 0; k < n / 2; k++) {
for (int l = 0; l < n - 1 - k - k; l++) {
int temp = mat[k][k + l];
mat[k][k + l] = mat[n - k - 1 - l][k];
mat[n - k - 1 - l][k] = mat[n - k - 1][n - k - 1 - l];
mat[n - k - 1][n - k - 1 - l] = mat[k + l][n - k - 1];
mat[k + l][n - k - 1] = temp;
}
}
}
```