rotate a matrix, matrix to 90 degree, square matrix rotation, progar, algorithm, interview question,

http://www.knowsh.com > Notes > Data Structure > Program to rotate a matrix
Priyank Program to rotate a square matrix by 90 degree Program to rotate the given NxN matrix by 90 degree. Language used C#.

Program to rotate a matrix

Program to rotate a matrix

Program to rotate a square matrix by 90 degree (Data Structure)

Introduction (Descriptive)

Program to rotate the given NxN matrix by 90 degree. Language used C#.

Details

    class Matrix
    {
        static void Main(string[] args)
        {
            int[,] matrix = new int[3, 3];
            matrix[0, 0] = 1;
            matrix[0, 1] = 2;
            matrix[0, 2] = 3;
            matrix[1, 0] = 4;
            matrix[1, 1] = 5;
            matrix[1, 2] = 6;
            matrix[2, 0] = 7;
            matrix[2, 1] = 8;
            matrix[2, 2] = 9;
            RotateMatrix(matrix);
        }

        /// <summary>
        /// This method rotates the input matrix
        /// This prints the input matrix and 
        /// matrix after rotation.
        /// </summary>
        /// <param name="matrix">input square matrix</param>
        static void RotateMatrix(int[,] matrix)
        {
            // get the length in one direction.
            // this is a square matrix so square-root 
            // of the array length is the array.
            int length = (int)Math.Sqrt((double)matrix.Length);

            // initialize a new array to save outout result.
            int[,] output = new int[length, length];

            // rotate the matrix
            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < length; j++)
                {
                    output[j, length-1 - i] = matrix[i, j];
                }
            }

            // print the input matrix
            Console.Write("Input Matrix: \n");
            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < length; j++)
                {
                    Console.Write(matrix[i, j]);
                    Console.Write("\t");
                }
                Console.Write("\n");
            }

            // print the rotated matrix
            Console.Write("Output Matrix: \n");
            for (int i = 0; i < length; i++)
            {
                for (int j = 0; j < length; j++)
                {
                    Console.Write(output[i, j]);
                    Console.Write("\t");
                }
                Console.Write("\n");
            }
        }
    }

 


About knowsh.com

We are tring to provide a common plateform to the students and professionals to share their knowledge among others because knowledge is the only thing that increase when it is shared.

Contact links