#LeetCode
题目描述
初次解法
- 递归思想
- 递归终止条件:矩阵形态为 1x1 与 2x2
- 递归迭代过程:矩阵形态NXN -> (N-2)X(N-2).分别是头尾截取一位。
- 递归操作过程:将矩阵四周看作4个一维数组,遍历交换这四个数组的元素。
- 如图:
class Solution {
public void rotate(int[][] matrix) {
recursion(matrix, 0, matrix[0].length-1, 0, matrix[0].length-1);
}
public void recursion(int[][] matrix, int urow,int drow, int lcol,int rcol){
//终止条件
if(drow - urow + 1 == 1) return ;
else if(drow - urow + 1 == 2) {
int temp = matrix[urow][lcol];
matrix[urow][lcol] = matrix[drow][lcol];
matrix[drow][lcol] = matrix[drow][rcol];
matrix[drow][rcol] = matrix[urow][rcol];
matrix[urow][rcol] = temp;
return ;
}
//递归操作
int i = 0;
while(i < rcol - lcol){
int temp = matrix[urow][lcol + i];
matrix[urow][lcol + i] = matrix[drow - i][lcol];
matrix[drow - i][lcol] = matrix[drow][rcol - i];
matrix[drow][rcol - i] = matrix[urow + i][rcol];
matrix[urow + i][rcol] = temp;
i++;
}
//递归迭代
recursion(matrix, urow + 1, drow - 1, lcol + 1, rcol - 1);
return ;
}
}
优化解法
- 题目要求不使用额外的内存空间。
- 递归比较占用栈内存,修改为迭代法看看。
- 改了发现也没节省多少内存。
class Solution {
public void rotate(int[][] matrix) {
// 初始状态额外负一层,以方便后续循环运行最外层的矩阵。
int urow = -1;
int drow = matrix[0].length;
int lcol = -1;
int rcol = matrix[0].length;
while(urow <= drow && lcol <= rcol){
urow = urow + 1;
drow = drow - 1;
lcol = lcol + 1;
rcol = rcol - 1;
int i = 0;
while(i < rcol - lcol){
int temp = matrix[urow][lcol + i];
matrix[urow][lcol + i] = matrix[drow - i][lcol];
matrix[drow - i][lcol] = matrix[drow][rcol - i];
matrix[drow][rcol - i] = matrix[urow + i][rcol];
matrix[urow + i][rcol] = temp;
i++;
}
}
return;
}
}
三次解法(官方)
- 用翻转代替旋转
- 图形变换:矩阵翻转90度=矩阵沿着水平轴翻转->矩阵再沿着主对角线翻转
class Solution {
public void rotate(int[][] matrix) {
// 先水平翻转 在主对角线翻转
int n = matrix.length;
//水平翻转
for(int i = 0; i < n / 2; i++){
for(int j = 0; j < n; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[n-i-1][j];
matrix[n-i-1][j] = temp;
}
}
//主对角线翻转
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
return;
}
}