Java实现MXN矩阵顺时针旋转

编程入门 行业动态 更新时间:2024-10-15 08:20:06

Java实现MXN<a href=https://www.elefans.com/category/jswz/34/1769510.html style=矩阵顺时针旋转"/>

Java实现MXN矩阵顺时针旋转

矩阵,可以看做是一个二维数组,如何实现一个MXN的矩阵旋转,如顺时针旋转90°,180°,270°。

3X4 矩阵 :

int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

顺时针90°,为4X3矩阵:{{9, 5, 1}, {10, 6, 2}, {11, 7, 3}, {12, 8, 4}}

顺时针180°,为3X4矩阵:{{12, 11, 10, 9}, {8, 7, 6, 5}, {4, 3, 2,1}}

顺时针270°,为4X3矩阵:{{4, 8, 12}, {3, 7, 11}, {2, 6, 10}, {1, 5, 9}}

代码如下:

package com.yx.test.util;public class MatrixUtil {public enum Rotation {/*** 不旋转*/ROTATION_0,/*** 右转90度*/ROTATION_90,/*** 右转180度*/ROTATION_180,/*** 右转270度*/ROTATION_270}/*** 点阵旋转** @param ori      原始点阵* @param rotation 旋转后点阵* @return 旋转后的点阵*/private static int[][] rotation(int[][] ori, Rotation rotation) {if (rotation == null || ori == null) {return null;}int row = ori.length;int col = ori[0].length;int[][] ret = null;switch (rotation) {case ROTATION_0:ret = ori;break;case ROTATION_90:ret = new int[col][row];for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {ret[j][row - 1 - i] = ori[i][j];}}break;case ROTATION_180:ret = new int[row][col];for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {ret[row - 1 - i][col - 1 - j] = ori[i][j];}}break;case ROTATION_270:ret = new int[col][row];for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {ret[col - 1 - j][i] = ori[i][j];}}break;default:break;}return ret;}/*** 打印矩阵* @param matrix 待打印矩阵*/private static void printMatrix(int[][] matrix) {if (matrix != null) {int row = matrix.length;int col = matrix[0].length;for (int i = 0; i < row; i++) {for (int j = 0; j < col; j++) {System.out.print(matrix[i][j] + " ");}System.out.println();}System.out.println();}}public static void main(String[] args) {int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};printMatrix(matrix);int[][] matrix90 = rotation(matrix, Rotation.ROTATION_90);printMatrix(matrix90);int[][] rotationMatrix180 = rotation(matrix, Rotation.ROTATION_180);printMatrix(rotationMatrix180);int[][] rotationMatrix270 = rotation(matrix, Rotation.ROTATION_270);printMatrix(rotationMatrix270);}
}

转换的关系式可以通过坐标系转换的思想理解。

更多推荐

Java实现MXN矩阵顺时针旋转

本文发布于:2024-02-26 09:16:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1701996.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:矩阵   顺时针   Java   MXN

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!