You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up:Could you do this in-place?
算法分析
方法一
- 將原始矩陣中的元素復制到新矩陣中
- 矩陣中元素位置計算:橫縱坐標分別計算
- 原始矩陣中橫坐標為新矩陣中縱坐標
- 原始矩陣中縱坐標j為新矩陣中height-j-1坐標
Java代碼
public class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
int height = matrix.length;
int weight = matrix[0].length;
if (height != weight) return;
int[][] temp = new int[weight][height];
for (int i = 0; i < height; i ++) {
for (int j = 0; j < weight; j ++) {
temp[i][j] = matrix[i][j];
}
}
for (int i = 0; i < height; i ++) {
for (int j = 0; j < weight; j ++) {
matrix[i][j] = temp[height - j- 1][i];
}
}
}
}
方法二:
原地坐標轉換。如圖所示:

原地坐標轉換
Java代碼
public class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;
int height = matrix.length;
int weight = matrix[0].length;
if (height != weight) return;
int temp = 0;
//原地坐標轉換
for (int i = 0; i < height / 2; i ++) {
for (int j = i; j < height - 1 - i; j ++) {
temp = matrix[i][j];
matrix[i][j] = matrix[height - j - 1][i];
matrix[height - j - 1][i] = matrix[height - i - 1][height - j - 1];
matrix[height - i - 1][height - j - 1] = matrix[j][height - i - 1];
matrix[j][height - i - 1] = temp;
}
}
}
}