博文中会简要介绍Leetcode P0048题目分析及解题思路。
“Rotate Image”是一道考验基本功的题目,有很多种解法,如何用比较简单的代码完成任务是这道题的重点。
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] ]
这里采取的思路是,以四个顶点为基点,每次对四条边进行旋转。在某一条边上的所有点,都可以写出以下一个顶点为基点的坐标表达式,然后内循环四次将所有的相应点位更新,而外循环只需要循环一次边长即可完成对整个四条边的更新,最后最外循环由外而内顺序访问环的起点。
以下是Java的题解代码实现。
class Solution {
public void rotate(int[][] matrix) {
if (matrix == null || matrix.length <= 1)
return;
int row = matrix.length, col = matrix[0].length;
for (int start=0; start<row/2; ++start) {
int x = start, y = start;
// 确立当前方阵的四个顶点
// Corners Mapping
// int[][] corners = new int[][]
// {start, col-1-start}, {row-1-start, col-1-start}, {row-1-start, start}, {start, start};
while (y < col-1-start) {
int copied = matrix[x][y];
for (int itr=0; itr<4; ++itr) {
int nextX = corners[itr][0]+(y-start)*di[itr][0];
int nextY = corners[itr][1]+(y-start)*di[itr][1];
int temp = matrix[nextX][nextY];
matrix[nextX][nextY] = copied;
copied = temp;
}
++y;
}
}
return;
}
// Direction Mapping
// private int[][] di = new int[][]
// {1,0}, {0,-1}, {-1,0}, {0,1};
}