Thursday, July 30, 2009

C++ coding for rotating 2D array to 90 degrees clockwise.?

i'm having problem with writing a program for rotating a 2D array by 90 degrees clockwise.





Example:





1 2 3


4 5 6


7 8 9





to





7 4 1


8 5 2


9 6 3





i'm doing the rotation in function. please write the coding for rotation. TQ.

C++ coding for rotating 2D array to 90 degrees clockwise.?
No Kartoo is wrong, Only transposing would not rotate. To Rotate, you have to reflect the matrix . Refflection about horizontal axis will ratate the matrix clockwise while reflection about vertical axis will make it rotate counter clockwise,


I am giving you a pseodo code of rotation of m by n matrix.





for(i=0; i%26lt;m;i++)


for(j=0; j%26lt;n; j++)


newArray[i][j]=oldArray[j][m-i+1];


This will cause the matrix to rotate counter-clockwise, itnerchange of i and j transposes the matrix while sustituting i by m-i+1 causes a reflection respect to vertical axis.
Reply:public static int[][] transpose(int[][] a, int m, int n)


{


// create new matrix


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


for (int i = 0; i %26lt; n; i++)


for (int j = 0; j %26lt; m; j++)


b[i][j] = a[j][i];





return b;


}





main()


{


int a[3][3];


for(int i=0;i%26lt;3;i++)


{


for(int j=0;j%26lt;3;j++)


{


cin%26gt;%26gt;a[i][j];


}


}





a = transpose(a, 3, 3);





}
Reply:in your example you have give 3D matrix





2D array looks like





1 2





3 4





(0r)





1 6





2 7





3 8





4 9





5 10





so i think the above code needs to be reconstructed.





When the no. of rows and columns are same it is easy. What if they are not equal?





Let us in this dimension...


No comments:

Post a Comment