自己的思路:从外到内一圈圈顺时针旋转90度,坐标映射问题。
Leetcode讨论区有很多有趣巧妙的思路,列举两个点赞率较高思路:
1)上下颠倒,然后转置
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
2)转置,然后左右颠倒
若需要逆时针,则分别是:
1)左右颠倒,然后转置
2)转置,然后上下颠倒
[ref]
https://leetcode.com/discuss/20589/a-common-method-to-rotate-the-image
public class Solution { public void rotate1(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; int rowBeg = 0, rowEnd = matrix.length - 1; int colBeg = 0, colEnd = matrix[0].length - 1; while (rowBeg <= rowEnd) { int offset = colEnd - colBeg - 1; for (int j = 0; j <= offset; j++) { int save = matrix[rowBeg][colBeg + j]; matrix[rowBeg][colBeg + j] = matrix[rowEnd - j][colBeg]; matrix[rowEnd - j][colBeg] = matrix[rowEnd][colEnd - j]; matrix[rowEnd][colEnd - j] = matrix[rowBeg + j][colEnd]; matrix[rowBeg + j][colEnd] = save; } rowBeg++; rowEnd--; colBeg++; colEnd--; } } // first transpose, then flip the matrix horizontally public void rotate(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; int rows = matrix.length, cols = matrix[0].length; for (int i = 0; i < rows; i++) { for (int j = i + 1; j < cols; j++) { int tmp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = tmp; } } int half = cols / 2; for (int i = 0; i < rows; i++) { for (int j = 0; j < half; j++) { int tmp = matrix[i][j]; matrix[i][j] = matrix[i][cols -1 - j]; matrix[i][cols -1 - j] = tmp; } } } }