题目来源:https://leetcode.com/problems/rotate-image/
问题描述
48. Rotate Image
Medium
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
rotate the input matrix in-place such that it becomes:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
Example 2:
Given input matrix =
[
[ 5, 1, 9,11],
[ 2, 4, 8,10],
[13, 3, 6, 7],
[15,14,12,16]
],
rotate the input matrix in-place such that it becomes:
[
[15,13, 2, 5],
[14, 3, 4, 1],
[12, 6, 8, 9],
[16, 7,10,11]
]
------------------------------------------------------------
题意
不开辟新的O(n^2)的空间,将n×n的矩阵顺时针旋转90°
------------------------------------------------------------
思路
手写个3×3、4×4矩阵的旋转,仔细观察,发现旋转由以下两个步骤构成:
1. 旋转第一行除最后一个元素外的n-1个元素,每次旋转会涉及4个位置之间的轮转,经过(n-1)×4次旋转之后,矩阵外面的边框旋转完成;
2. 递归旋转内部的(n-2)×(n-2)矩阵。
下面是一个图示。
1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 |
顺时针旋转90°:
13 | 9 | 5 | 1 |
14 | 10 | 6 | 2 |
15 | 11 | 7 | 3 |
16 | 12 | 8 | 4 |
同一色系表示同一个轮转片。n×n矩阵外围共(n-1)个轮转片,每个轮转片包含4个单元格。内部的(n-2)×(n-2)矩阵(白色)用递归方式处理。
------------------------------------------------------------
代码
class Solution {
public void dfsRotate(int[][] matrix, int x, int n)
{
if (n <= 1)
{
return;
}
int tmp = 0;
for (int i=0; i<n-1; i++)
{
tmp = matrix[x][x + i];
matrix[x][x + i] = matrix[x + n-1-i][x];
matrix[x + n-1-i][x] = matrix[x + n-1][x + n-1-i];
matrix[x + n-1][x + n-1-i] = matrix[x + i][x + n - 1];
matrix[x + i][x + n - 1] = tmp;
}
dfsRotate(matrix, x + 1, n - 2);
}
public void rotate(int[][] matrix) {
int n = matrix.length;
dfsRotate(matrix, 0, n);
}
}