hot100-48 旋转图像
题目描述
给定一个 n × n 的二维矩阵 matrix 表示一个图像。请你将图像顺时针旋转 90 度。
你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要 使用另一个矩阵来旋转图像。
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[[7,4,1],[8,5,2],[9,6,3]]
思路
两次反转
- 先沿右上 - 左下的对角线翻转(270° + 一次镜像),
- 再沿水平中线上下翻转(-180° 一次镜像),可以实现顺时针 90 度的旋转效果
- 沿对角线反转时,横纵坐标的和为
n-1
代码
class Solution {
public void rotate(int[][] matrix) {
if(matrix.length==0 || matrix[0].length!=matrix.length)return;
//1.先 右上-左下反转---270度镜像
int col = matrix.length;
for(int i=0;i<col;i++){
for(int j=0;j<col-i;j++){ //只反转一半
int temp = matrix[i][j];
matrix[i][j] = matrix[col-1-j][col-1-i];
matrix[col-1-j][col-1-i] = temp;
}
}
//2.再沿水平中线 180度 反转,可实现90度顺时针旋转
for(int i=0;i<col/2;i++){
for(int j=0;j<col;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[col-1-i][j];
matrix[col-1-i][j] = temp;
}
}
}
}
/**
注意:沿对角线反转时,横纵坐标的和为 n-1
**/