48. 旋转图像 C#实现-输入: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]] 提示:

时间:2024-10-27 10:24:42
  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

public class Solution {
    public void Rotate(int[][] matrix) {
        int n = matrix.Length;

        // 首先进行上下翻转
        for (int i = 0; i < n / 2; i++)
        {
            // 交换上下行
            int[] temp = matrix[i];
            matrix[i] = matrix[n - i - 1];
            matrix[n - i - 1] = temp;
        }

        // 然后进行对角线翻转
        for (int i = 0; i < n; i++)
        {
            for (int j = i; j < n; j++)
            {
                // 交换对角线元素
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }
}