# 48. Rotate Image

[Link](https://leetcode.com/problems/rotate-image/submissions/)

**Solution**

matrix rotate method overview

***clock wise:***

1st step : Reverse all row, swap(matrix\[i], matrix\[n-1-i] for all i = 0 \~ n/2

1 2 3         7 8 9\
4 5 6   ->   4 5 6\
7 8 9         1 2 3

2nd step : swap(matrix\[i]\[j] , matrix\[j]\[i]) for i = 0->n-1, for j = i+1 -> n-1

7 8 9      7  4  1\
4 5 6  -> 8  5  2\
1 2 3      9  6  3

```
public void rotate(int[][] matrix) {
       //reverse matix row
        int n = matrix.length;
        for(int i = 0; i < n/2; i++){
            //swap all element in matrix[i] to matrix[n-i]
            int[] temp = matrix[i];
            matrix[i] = matrix[n-1-i];
            matrix[n-1-i] = temp;
        }
        
        //swap matrix[i][j], matrix[j][i] for all i != j
        for(int i = 0; i < n; i++){
            //j = i+1 is crucial to let the swap not duplicated
            for(int j = i+1; j < n; j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }
```

***Anti-clock wise:***

1st step : Reverse all element in the raw

1 2 3         3 2 1\
4 5 6   ->   6 5 4\
7 8 9         9 8 7&#x20;

2nd step : swap(matrix\[i]\[j] , matrix\[j]\[i]) for i = 0->n-1, for j = i+1 -> n-1

3 2 1      3  6  9\
6 5 4  -> 2  5  8\
9 8 7      1  4  7

```
    public void rotate(int[][] matrix) {
       //reverse matix colum
        int n = matrix.length;
        for(int i = 0; i < n; i++){
            //swap all element in matrix[i] to matrix[n-i]
            for(int j = 0; j < n/2; j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[i][n-1-j];
                matrix[i][n-1-j] = temp;
            }
            
        }
        
        //swap matrix[i][j], matrix[j][i] for all i != j
        for(int i = 0; i < n; i++){
            //j = i+1 is crucial to let the swap not duplicated
            for(int j = i+1; j < n; j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }
```
