一、问题描述
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?
二、问题分析
先沿着副对角线翻转一次;再沿着水平对称轴翻转一次。
三、算法代码
public class Solution {
public void rotate(int[][] matrix) {
int len = matrix.length;
//沿副对角线旋转
for(int i = 0; i <= len - 1; i++){
for(int j = 0; j < len - i; j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[len - 1 - j][len - 1 - i];
matrix[len - 1 - j][len - 1 - i] = tmp;
}
}
//沿水平中线翻转
for(int i = 0; i < len / 2; i++){
for(int j = 0; j <= len - 1; j++){
int tmp = matrix[i][j];
matrix[i][j] = matrix[len - i - 1][j];
matrix[len - i - 1][j] = tmp;
}
}
}
}
本文介绍了一种高效的二维矩阵按顺时针方向旋转90度的算法,并提供了详细的实现步骤。通过两次翻转操作——首先沿副对角线翻转,然后沿水平轴翻转,实现了矩阵的原地旋转。
1726

被折叠的 条评论
为什么被折叠?



