问题描述
题目链接:https://leetcode-cn.com/problems/rotate-image/
原文
You are given an n × n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Follow up: Could you do this in-place?
大意:给一个 n * n 的二维矩阵表示的图像,将这个图像顺时针旋转90°。
例如给一个 3 * 3矩阵,
[
[1,2,3 ]
[4,5,6 ]
[7,8,9 ]
]
顺时针旋转90°后,
[
[7,4,1 ]
[8,5,2 ]
[9,6,3 ]
]
思路分析
首先最容易想到的就是创建一个新的n * n矩阵来存储结果,然后将原矩阵的对应行存储到结果矩阵的对应列即可。经过简单分析,可以发现原矩阵中**(i,j)位置的元素,在结果矩阵中位置应该是(j,n-1-i)**。有了对应关系我们可以很快写出如下的代码:
/*
* 模拟法:时间复杂度 O(n²) ,空间复杂度 O(n²)
*/
public static void rotate5(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
if (m != n)
return;
int[][] result = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {