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;
}
}
}
}