数据结构与算法(Java) 23:旋转正方形矩阵

题目 给定一个整型正方形矩阵matrix,请把该矩阵调整成顺时针旋转90度的样子。

要求 额外空间复杂度为O(1)。

思路 一圈儿一圈儿的转,类似于旋转打印矩阵。用递归方法实现。

package algorithm.section4;

public class RotateMatrix {
    public static void rotate(int[][] matrix){
        int top = 0;
        int bottom = matrix.length - 1;
        int left = 0;
        int right = matrix[0].length - 1;

        printEdge(matrix, top, bottom, left, right);
    }

    public static void printEdge(int[][] matrix, int top, int bottom, int left, int right){
        if (top < bottom && left < right){
            for (int i = 0; i < right - left; i++){
                int flag = matrix[top][left + i];
                matrix[top][left + i] = matrix[bottom - i][left];
                matrix[bottom - i][left] = matrix[bottom][right - i];
                matrix[bottom][right - i] = matrix[top + i][right];
                matrix[top + i][right] = flag;
            }
        } else if (top < bottom) {
            for (int i = 0; i <= bottom / 2; i++){
                int flag = matrix[top + i][left];
                matrix[top + i][left] = matrix[bottom - i][left];
                matrix[bottom - i][left] = flag;
            }
        } else if (left < right) {
            for (int i = 0; i <= right / 2; i++){
                int flag = matrix[top][left + i];
                matrix[top][left + i] = matrix[top][right - i];
                matrix[top][right - i] = flag;
            }
        } else return;
        printEdge(matrix, top + 1, bottom - 1, left + 1, right - 1);
    }

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

    public static void main(String[] args) {
        int[][] matrix = {
                { 1, 2, 3, 4 },
                { 5, 6, 7, 8 },
                { 9, 10, 11, 12 },
                { 13, 14, 15, 16 }
        };
        print(matrix);
        rotate(matrix);
        System.out.println("\n=========");
        print(matrix);
    }
}
发布了149 篇原创文章 · 获赞 36 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/Dorothy_Xue/article/details/105668166