Pages

Monday, May 20, 2013

C#: Rotate a matrix to 90 degree.

Rotate a matrix to 90 degree. This program example works only for a matrix with number of columns equal to the number of rows.

//Matrix class
class MatrixTurn
    {
        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);
          
        }

        static void Main(string[] args)
        {
            int[,] arry =  { {  1, 2,3}, {  4, 5,6 },{7,8,9}  };
            Console.WriteLine("Given Matrix");
            MatrixTurn mtx = new MatrixTurn();
            mtx.DisplayMatrix(arry,3,3);

            mtx.Degree90Matrix(arry,3,3);

        }
    }


Input:
Given Matrix
1  2  3
4  5  6
7  8  9

Output Matrix:
7  4  1
8  5  2
9  6  3

1 comment: