java – 将矩阵旋转到位

前端之家收集整理的这篇文章主要介绍了java – 将矩阵旋转到位前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在解决旋转NxN矩阵的问题.

似乎我的代码进行了旋转,但在图像上留下了X.
所以我猜它正在不正确地旋转边缘.
我附加了两个图像作为样本输入和输出.

我的代码出了什么问题:

public static void rotateRight(float[][] img){
    for (int i=0; i<N/2; i++){
        for (int j=i; j<N-i; j++){
            int J_COMP = N-j-1; //complement of J
            int LEFT = i;
            int RIGHT = N-i-1;
            int TOP = i;
            int BOTTOM = N-i-1;

            float temp = img[J_COMP][LEFT];
            img[J_COMP][LEFT] = img[BOTTOM][J_COMP];
            img[BOTTOM][J_COMP] = img[j][RIGHT];
            img[j][RIGHT] = img[TOP][j];
            img[TOP][j] = temp;
        }
    }       
}

解决方法

您正在旋转主对角线两次.

修复内循环(参见“修复”评论)

package tests.StackOverflow;

public class Question_20773692 {

    private static int N;

    public static void main(String[] args) {

        float[][] img;
        int count;

        N=3;
        count = 0;
        img = new float[N][N];
        for(int i=0; i<N; ++i) {
            for(int j=0; j<N; ++j) {
                img[i][j] = count++;
            }
        }

        printImg(img);

        rotateRight(img);

        printImg(img);

    }

    public static void printImg(float[][] img) {
        for(int j=0; j<N; ++j) {
            System.out.print("-");
        }
        System.out.println();
        for(int i=0; i<N; ++i) {
            for(int j=0; j<N; ++j) {
                System.out.print((int)(img[i][j]));
            }
            System.out.println();
        }
        for(int j=0; j<N; ++j) {
            System.out.print("-");
        }
        System.out.println();   }

    public static void rotateRight(float[][] img){
        for (int i=0; i<N/2; i++){
            for (int j=i; j<N-i; j++){
            //for (int j=i+1; j<N-i; j++){ //fix
                int J_COMP = N-j-1; //complement of J
                int LEFT = i;
                int RIGHT = N-i-1;
                int TOP = i;
                int BOTTOM = N-i-1;

                float temp = img[J_COMP][LEFT];
                img[J_COMP][LEFT] = img[BOTTOM][J_COMP];
                img[BOTTOM][J_COMP] = img[j][RIGHT];
                img[j][RIGHT] = img[TOP][j];
                img[TOP][j] = temp;
            }
        }       
    }
}

猜你在找的Java相关文章