顺时针旋转数组

14

我有一个二维数组,需要将其顺时针旋转90度,但是我一直收到“数组下标越界”的错误...

public int[][] rotateArray(int[][] arr) {
    // first change the dimensions vertical length
    // for horizontal length and vice versa
    int[][] newArray = new int[arr[0].length][arr.length];

    // invert values 90 degrees clockwise by starting
    // from button of array to top and from left to right
    int ii = 0;
    int jj = 0;
    for (int i = 0; i < arr[0].length; i++) {
        for (int j = arr.length - 1; j >= 0; j--) {
            newArray[ii][jj] = arr[i][j];
            jj++;
        }
        ii++;
    }
    return newArray;
}

这不是矩阵旋转,而是矩阵转置http://en.wikipedia.org/wiki/Transpose,它是沿主对角线的反射。 - polygenelubricants
这只是反转了行,但是对于每个i,jj都必须设置为0。 要旋转arr[i][j]中的i和j(不要忘记将jj设置为0)。 - Maciej Hehl
11个回答

-2
public class Sample {

    /**
     * @param args
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub      
        int mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
        printMatrix(mat);

        int antiClockwiseMatrix[][] = rotateAntiClockwiseMatrix(mat);
        printMatrix(antiClockwiseMatrix);
        int clockwiseMatrix[][] = rotateClockwiseMatrix(mat);
        printMatrix(clockwiseMatrix);

        // rotateAntiMatrix(mat);
    }

    public static void printMatrix(int mat[][]) {
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                System.out.print(mat[i][j] + "\t");
            }
            System.out.print("\n");
        }
        System.out.print("\n");

    }

    static public int[][] rotateAntiClockwiseMatrix(int mat[][]) {
        int rows = mat.length;
        int cols = mat[0].length;
        int newMat[][] = new int[cols][rows];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                newMat[j][i] = mat[i][j];
            }
        }

        return newMat;
    }

    static public int[][] rotateClockwiseMatrix(int mat[][]) {
        int newMat[][] = rotateAntiClockwiseMatrix(mat);
        int finMat[][] = new int[newMat.length][newMat[0].length];
        for (int i = 0; i < newMat.length; i++) {
            int n = 0;
            for (int j = newMat[0].length - 1; j >= 0; j--) {
                finMat[i][n] = newMat[i][j];
                n++;
            }
        }

        return finMat;

    }
}

非常简单的逻辑来使矩阵顺时针或逆时针旋转。 - Ashwini Kaushik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接