题目:给你一幅由N * N矩阵表示的图像,其中每个像素的大小为4字节。请你设计一种算法,将图像旋转90度。
不占用额外内存空间能否做到?
示例1:
给定matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
示例2:
给定matrix =
[
[5,1,9,11],
[2,4,8,10],
[13,3,6,7],
[15,14,12,16]
],
原地旋转输入矩阵,使其变为:
[
[15,13,2,5],
[14,3,4,1],
[12,6,8,9],
[16,7,10,11]
]
1. 思考
如下图可以发现,矩阵的旋转其实就是依次对每层像素进行迁移,对于每层像素,top移到right,right移到bottom,bottom移到left。
所以总体的处理思路就是依次对每层像素点做迁移处理。
以top层像素点index作为参考,推导出对应的right,bottom,left像素点的index,即可解决问题。
由图可知,对于N * N矩阵,共有N / 2层需要做像素点迁移,即layer位于[0, N/2)区间内。
对于layer层像素,top需要迁移的像素点[layer, layer],[layer, layer + 1],[layer, layer + 2]……[layer, N - layer - 2]。
对于top像素点[x, y],推导出对应right,bottom,left像素点index。下图展示了几对像素点的位置。
对于每层的处理,是由黄色位置完成后,再处理绿色位置这样一个顺序进行的,取top像素点index为[x, y],通过上图可以发现right,bottom,left像素点与top像素点的关系。
1. right的row和top的col是一致的。
2. top的col与bottom的col和为N - 1。
3. left的row与right的row和为N - 1。
根据以上三种关系,假定当前层layer,top像素[x, y]对应的right,bottom,left像素位置如下。
right:[y, N - 1 - layer]
bottom:[N - 1 - layer, N - 1 - y]
left:[N - 1 - y, layer]
因为需要顺时针旋转矩阵,所以需要将top移到right,right移到bottom,bottom移到left,迁移策略如下:
取临时变量tmp记录top值,left移到top,bottom移到left,right移到bottom,tmp赋值给right,这样就完成了一个像素点的旋转。
2. 代码实现
public void rotate(int[][] matrix) {
if (matrix.length < 2) {
return;
}
int length = matrix.length;
// layerCount记录有几层像素需要旋转
int layerCount = length / 2;
// 依次遍历每层像素
for (int layer = 0; layer < layerCount; layer++) {
// 依次旋转当前层top像素
for (int col = layer; col < length - layer - 1; col++) {
// 记录top值
int tmp = matrix[layer][col];
// top: matrix[layer][col]
// left: matrix[length - 1 - col][layer]
// bottom: matrix[length - 1 - layer][length - 1 - col];
// right: matrix[col][length - 1 - layer]
// left移到top
matrix[layer][col] = matrix[length - 1 - col][layer];
// bottom移到left
matrix[length - 1 - col][layer] = matrix[length - 1 - layer][length - 1 - col];
// right移到bottom
matrix[length - 1 - layer][length - 1 - col] = matrix[col][length - 1 - layer];
// tmp赋值给right
matrix[col][length - 1 - layer] = tmp;
}
}
}