Rotate the matrix in place

I decide to rotate the NxN matrix in place .

It seems that my code is making a rotation, but leaving X above the image.
Therefore, I assume that it rotates the edges incorrectly. I am attaching two images as an input and output sample.

enter image description hereenter image description here

What is wrong with my code:

public static void rotateRight(float[][] img){ for (int i=0; i<N/2; i++){ for (int j=i; j<Ni; j++){ int J_COMP = Nj-1; //complement of J int LEFT = i; int RIGHT = Ni-1; int TOP = i; int BOTTOM = Ni-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; } } } 
+7
java arrays image-rotation
source share
3 answers

You rotate the main diagonals twice.

Fix inner loop (see comment "Fix")

 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<Ni; j++){ //for (int j=i+1; j<Ni; j++){ //fix int J_COMP = Nj-1; //complement of J int LEFT = i; int RIGHT = Ni-1; int TOP = i; int BOTTOM = Ni-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; } } } } 
+1
source share

The rotation of the matrix in place ... I think it should work.

 public void rotate(ArrayList<ArrayList<Integer>> a) { int n=a.size()/2; for(int i=1;i<=n;i++){ ArrayList<Integer>temp=a.get(i-1); a.set(i-1,a.get(a.size()-i)); a.set(a.size()-i,temp); } for(int i=0;i<a.size();i++){ for(int j=i+1;j<a.get(0).size();j++){ a.get(i).set(j,a.get(i).get(j)^a.get(j).get(i)); a.get(j).set(i,a.get(i).get(j)^a.get(j).get(i)); a.get(i).set(j,a.get(i).get(j)^a.get(j).get(i)); } } } 
+1
source share

If you want to rotate the image, I would recommend using java.awt.geom.AffineTransform

If this is a logical question about matrix rotation, I believe that you can correct your result by replacing (one or both?) < With <= . Also note that your image has a size of 309x309 (odd numbers!), And you left the middle that is not adjusted with N/2 . Possible solution: add 1 - replace N/2 with

N % 2 == 0 ? N / 2 : N / 2 + 1

0
source share

All Articles