一. 题目

二. 思路

  • 先上下翻转,再主对角线翻转。

三. 代码

class Solution
{
    void swap(int[][] a, int x1, int y1, int x2, int y2)
    {
        int temp = a[x1][y1];
        a[x1][y1] = a[x2][y2];
        a[x2][y2] = temp;
    }

    public void rotate(int[][] matrix)
    {
        int n = matrix.length;
        int up = 0, down = n - 1;
        while (up < down)//水平翻转
        {
            for (int i = 0; i < n; ++i)
                swap(matrix, up, i, down, i);
            ++up;
            --down;
        }

        //主对角线翻转
        for (int i = 0; i < n; ++i)
            for (int j = 0; j < i; ++j)
                swap(matrix, i, j, j, i);
    }
}