Rotate Image
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]
]
分析:
本题的关键是找到几个互换点之间位置的关系。
1 public class Solution { 2 /** 3 * @param matrix: 4 * A list of lists of integers 5 * @return: Void 6 */ 7 public void rotate(int[][] matrix) { 8 if (matrix == null || matrix.length == 0) return; 9 int n = matrix.length - 1; 10 for (int i = 0; i < (n + 1) / 2; ++i) { 11 for (int j = i; j < n - i; ++j) { 12 int t = matrix[i][j]; 13 matrix[i][j] = matrix[n - j][i]; 14 matrix[n - j][i] = matrix[n - i][n - j]; 15 matrix[n - i][n - j] = matrix[j][n - i]; 16 matrix[j][n - i] = t; 17 } 18 } 19 } 20 }
对于一个正方形边上的四个对应点,它们有下面的关系:n = 边长 - 1
上: (x, y)
下:(n - x, n - y)
左:(n - y, x)
右:(y, n - x)
另一种解法:
The idea was firstly transpose the matrix and then flip it symmetrically. For instance,
1 2 3
4 5 6
7 8 9
after transpose, it will be swap(matrix[i][j], matrix[j][i])
1 4 7
2 5 8
3 6 9
Then flip the matrix horizontally. (swap(matrix[i][j], matrix[i][matrix.length-1-j])
7 4 1
8 5 2
9 6 3
Hope this helps.
1 public class Solution { 2 public void rotate(int[][] matrix) { 3 for(int i = 0; i<matrix.length; i++){ 4 for(int j = i; j<matrix[0].length; j++){ 5 int temp = 0; 6 temp = matrix[i][j]; 7 matrix[i][j] = matrix[j][i]; 8 matrix[j][i] = temp; 9 } 10 } 11 for(int i =0 ; i<matrix.length; i++){ 12 for(int j = 0; j<matrix.length/2; j++){ 13 int temp = 0; 14 temp = matrix[i][j]; 15 matrix[i][j] = matrix[i][matrix.length-1-j]; 16 matrix[i][matrix.length-1-j] = temp; 17 } 18 } 19 } 20 }

浙公网安备 33010602011771号