一年后,从头再看矩阵转换

废话不多说,直接上代码:

package com.miaoqiang.code;

/**
 * @Author: 苗晓强
 * @Date: 2021/11/29 22:44
 * 需求:3行4列的二维数组,顺时针旋转90° 具体如下:
 * 旋转前
 *  1   2   3   4
 *  5   6   7   8
 *  9   10  11  12
 *  旋转后
 *  9     5     1
 * 10     6     2
 * 11     7     3
 * 12     8     4
 */
public class ChangeMatrix {
    public static void main(String[] args) {
        int number = 0;
        int row = 3;
        int column = 4;
        int[][] matrix = new int[row][column];
        System.out.println("====矩阵转换前数据===");
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                number++;
                System.out.print((matrix[i][j] = number) + "    ");
            }
            System.out.println();
        }
        //矩阵转换
        int [][] temp = changeMatrix(matrix);
        System.out.println("===矩阵转换后数据===");
        printMarix(temp);
    }

    /**
     * 双层for循环遍历打印二维数组
     * @param temp
     */
    private static void printMarix(int[][] temp) {
        for (int i = 0; i < temp.length; i++) {
            for (int j = 0; j < temp[0].length; j++) {
                System.out.print(temp[i][j] + "     ");
            }
            System.out.println();
        }
    }

    private static int[][] changeMatrix(int[][] matrix) {
        //矩阵旋转,首先要将原有的行列要互换
        int [][] temp = new int [matrix[0].length][matrix.length];
        /**
         *矩阵顺时针九十度转换,可以看做矩阵的左上角固定不动,转动矩阵其他位置的值 
         * 变量 i 代表原有的行 j 代表原有的列 如果要实现矩阵转换
         * 此时就需要引入第三个变量 m
         */
        int m = matrix.length - 1; //原有矩阵的行数作为转换后矩阵的列数 再加上 数组下标以 0 开始 故,需要减一
        for (int i = 0; i < matrix.length; i++,m--) {
            for (int j = 0; j < matrix[0].length; j++) {
                temp[j][m] = matrix[i][j];
            }
        }
        return temp;
    }
}

猜你喜欢

转载自blog.csdn.net/mnimxq/article/details/121644452