第七题:将N * N的举证(正方形)顺时针旋转90度

版权声明:Please make the source marked https://blog.csdn.net/qq_31807385/article/details/86179562

题目要求:

将N * N的举证(正方形)顺时针旋转90度,如下图,将左边的矩阵旋转为右边的矩阵; 要求额外空间复杂度为O(1),

也即原地旋转。

1 2 3   7 4 1
4 5 6   8 5 2
7 8 9   9 6 3

代码实现与分析:

package com.isea.brush.rotate;

/**
 * 顺时针旋转N * N的矩阵(方阵)
 */
public class RotateMetric {

    /**
     * 打印矩阵
     * @param metric
     */
    public static void rotateMetric(int[][] metric) {
        
        if (metric == null){
            throw new IllegalArgumentException("The metric is empty...");
        }
        int a = 0;
        int b = 0;
        int c = metric.length - 1;
        int d = metric[0].length - 1;

        while (a < c) {
            rotateMetric(metric, a++, b++, c --, d --);
        }
    }

    /**
     * 交换最外圈,(a,b) -> (c,d)
     *
     * @param metric
     * @param a
     * @param b
     * @param c
     * @param d
     */
    private static void rotateMetric(int[][] metric, int a, int b, int c, int d) {
        int times = d - b;
        int tmp = 0;
        for (int i = 0; i < times; i++) {
            tmp = metric[a][b + i];
            metric[a][b + i] = metric[c - i][b];
            metric[c - i][b] = metric[c][d - i];
            metric[c][d - i] = metric[a + i][d];
            metric[a + i][d] = tmp;
        }
    }

    public static void printMertic(int[][] mertic) {
        for (int i = 0; i < mertic.length; i++) {
            for (int j = 0; j < mertic[i].length; j++) {
                System.out.print(mertic[i][j] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        int[][] mertic = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        printMertic(mertic);
        rotateMetric(mertic);
        System.out.println("----------------");
        printMertic(mertic);
    }

    /**
     *1 2 3 
     * 4 5 6 
     * 7 8 9 
     * ----------------
     * 7 4 1 
     * 8 5 2 
     * 9 6 3 
     */
}

猜你喜欢

转载自blog.csdn.net/qq_31807385/article/details/86179562