For Rotating a matrix to 90 degrees in-place, it should be a square matrix that is same number of Rows and Columns otherwise in-place solution is not possible and requires changes to row/column.
For a square array, we can do this inplace. First, notice that a 90 degree clockwise rotation is a matrix transpose, followed by a reflection (or if you prefer, a rotation), along the center of the array in the vertical direction. This leads to the following algorithm in C#
Matrix Class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
class Matrix { public void DisplayMatrix(int[,] arry, int m, int n) { for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { Console.Write(arry[i, j] + " "); } Console.WriteLine(); } Console.WriteLine(); } public void Degree90Matrix(int[,] arry, int m, int n) { int j = 0; int p = 0; int q = 0; int i = m - 1; int[,] rotatedArr = new int[m, n]; //for (int i = m-1; i >= 0; i--) for (int k = 0; k < m; k++) { while (i >= 0) { rotatedArr[p, q] = arry[i, j]; q++; i--; } j++; i = m - 1; q = 0; p++; } DisplayMatrix(rotatedArr, m, n); } } |
C# Program:
1 2 3 4 5 6 7 8 9 10 |
int[,] arry = { { 4, 1, 3 }, { 1, 8, 6 }, { 6, 1, 9 } }; Console.WriteLine("Entered Matrix"); Matrix mtx = new Matrix(); mtx.DisplayMatrix(arry, 3, 3); mtx.Degree90Matrix(arry, 3, 3); Console.ReadLine(); |
Output: