Rotate Image

Problem:

You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise).

Example
Given a matrix

[
    [1,2],
    [3,4]
]

rotate it by 90 degrees (clockwise), return

[
    [3,1],
    [4,2]
]

Leetcode link
Lintcode link

Solution:

There are two solutions.
The idea of the first method is to divide the matrix into four smaller matrix, then move each sub-matrix to the rotated position
The idea of the second method is to rotate layer by layer, from the outmost layer to the inner most layer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/*************************************************************************
> File Name: RotatedImage.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Fri 13 Nov 13:56:37 2015
************************************************************************/


public class RotatedImage{
//Solution 1
public void rotate(int[][] matrix) {
int length = matrix.length;

for (int i = 0; i < length / 2; i++){
for (int j = 0; j < (length + 1) / 2; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[length - 1 - j][i];
matrix[length - 1 - j][i] = matrix[length - 1 - i][length - 1 - j];
matrix[length - 1 - i][length - 1 - j] = matrix[j][length - 1 - i];
matrix[j][length - 1 - i] = temp;
}
}
}

//Solution 2
public void rotate(int[][] matrix) {
int length = matrix.length;

for (int layer = 0; layer < length / 2; layer++){
int last = length - 1 - layer;
for (int j = layer; j < last; j++){
int offset = j - layer;
int temp = matrix[layer][j];
matrix[layer][j] = matrix[last - offset][layer];
matrix[last - offset][layer] = matrix[last][last - offset];
matrix[last][last - offset] = matrix[j][last];
matrix[j][last] = temp;
}
}
}
}