0

我在这里查看了顺时针旋转的算法,但我不能反过来做。所以基本上,对于顺时针旋转,你需要将转置乘以一个旋转矩阵,但是你如何做同样的事情呢?

这是我的代码:

public class rotation2 {

    public static int [][] multiplyMatrix(int [][] m1) {
        int [][] m2 = {{0,0,0,1},
                       {0,0,1,0},
                       {0,1,0,0},
                       {1,0,0,0}};
        int[][] result = new int[4][4];

        // multiply
        for (int i=0; i<4; i++)
            for (int j=0; j<4; j++)
                for (int k=0; k<4; k++)
                    result[i][j] += m1[i][k] * m2[k][j];

        return result;
    }

    public static int [][] multiplyMatrix2(int [][] m2) {
        int [][] m1 = {{0,0,0,1},
                       {0,0,1,0},
                       {0,-1,0,0},
                       {-1,0,0,0}};
        int[][] result = new int[4][4];

        // multiply
        for (int i=0; i<4; i++)
            for (int j=0; j<4; j++)
                for (int k=0; k<4; k++)
                    result[i][j] += m1[i][k] * m2[k][j];

        return result;
    }

    public static void printArray(int [][] array) {
        for(int row = 0; row < array.length; row++) {
            for(int col = 0; col < array[row].length; col++) {
                if (array[row][col] > 0) {
                    System.out.printf("1");
                } else {
                    System.out.printf("0");
                }
            }
            System.out.printf("\n");
        }
    }

    public static int [][] transpose(int [][] m1) {
        int m = 4;
        int n = 4;
        int c = 0;
        int d = 0;

        int[][] transpose = new int [n][m];

        for ( c = 0 ; c < m ; c++ ) {
            for ( d = 0 ; d < n ; d++ ) {
                transpose[d][c] = m1[c][d];
            }
        }
        return transpose;
    }

    public static void main(String[] args) {
        int [][] m1 = {{1,0,0,0},
                       {1,0,0,0},
                       {1,1,0,0},
                       {0,0,0,0}};

        int [][] transpose = transpose(m1);
        printArray(transpose);
        transpose = multiplyMatrix(transpose);
        printArray(transpose);

        int [][] transpose2 = transpose(m1);
        printArray(transpose2);
        transpose2 = multiplyMatrix(transpose2);
        printArray(transpose2);
    }
}

您不会为计数器时钟旋转转调,对吗?

4

1 回答 1

0

您要做的是(1)转置矩阵,(2)分别反转行(顺时针)或列(逆时针)。

您可以只使用双循环为单个单元格设置新值,同时执行这两个步骤。在代码中,这可能如下所示:

public static int[][] rotate(int[][] m, boolean left) {
    int rows = m.length, cols = m[0].length;
    int[][] m2 = new int[cols][rows]; // swap rows and cols
    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++)
            if (left) // rotate left
                m2[c][r] = m[r][cols - c - 1];
            else      // rotate right
                m2[c][r] = m[rows - r - 1][c];
    return m2;
}

有关更多信息和替代方法,请查看此相关问题的答案。

于 2013-02-16T21:31:17.953 回答