LeetCode: 48. Rotate Image

1. 原题链接

https://leetcode.com/problems/rotate-image/description/

2. 题目要求

给定一个由 n*n 的二维数组 matrix[ ] [ ] 构成的矩阵,将这个矩阵顺时针方向旋转90度,并输出。如下图所示

3. 解题思路

首先对每一行进行交换,得到上图中的中间结果;

然后再交换 关于对角线对称的元素:matrix [ i ][ j ] 和 matrix[ j ][ i ]。如下图所示:

4. 代码实现

public class RotateImage48 {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3, 5}, {4, 5, 6, 7}, {7, 8, 9, 9}, {2, 3, 4, 5}};
        rotate(matrix);
        for (int[] x : matrix) {
            for (int y : x)
                System.out.print(y + " ");
            System.out.println();
        }

    }

    public static void rotate(int[][] matrix) {
        int a = 0, b = matrix.length - 1;
        // 交换行
        while (a < b) {
            int[] temp = matrix[a];
            matrix[a] = matrix[b];
            matrix[b] = temp;
            a++;
            b--;
        }

        //交换对称元素
        for (int i = 0; i < matrix.length; i++) {
            for (int j = i + 1; j < matrix[i].length; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }


}

  

原文地址:https://www.cnblogs.com/huiAlex/p/8282415.html