Matrix Layer Rotation

Programming Language = C#

You are given a 2D matrix of dimension  and a positive integer . You have to rotate the matrix  times and print the resultant matrix. Rotation should be in anti-clockwise direction.

Rotation of a  matrix is represented by the following figure. Note that in one rotation, you have to shift elements by one step only.

You can check full question click here

Solution Matrix Layer Rotation

1) Get the number of ROW and COLUMN

2) Get the number of Loop

3) Get the number of Rotation based on the ROW, COLUMN and R

4) Start Clockwise Rotation – Move First Row,  Right Column, Move Last Row, Left Column

5) Get the final Matrix

static void matrixRotation(List<List<int>> matrix, int r)
        {
            int ROW = matrix.Count;
            int COLUMN = ((List<int>)matrix[0]).Count;
            int numLoop = ROW < COLUMN ? ROW / 2 : COLUMN / 2;
            for (int i = 0; i < numLoop; i++)
            {
                int numRotations = r % (2 * (ROW + COLUMN – 4 * i) – 4);
                for (int rotation = 0; rotation < numRotations; rotation++)
                {
                    //clockwise
                    for (int j = i; j < COLUMN – i – 1; j++)
                    {
                        int temp = matrix[i][j];
                        matrix[i][j] = matrix[i][j + 1];
                        matrix[i][j + 1] = temp;
                    }
                    // Rotate right column
                    for (int j = i; j < ROW – i – 1; j++)
                    {
                        int temp = matrix[j][COLUMN – i – 1];
                        matrix[j][COLUMN – i – 1] = matrix[j + 1][COLUMN – i – 1];
                        matrix[j + 1][COLUMN – i – 1] = temp;
                    }
                    // Rotate bottom row
                    for (int j = COLUMN – i – 1; j > i; j–)
                    {
                        int temp = matrix[ROW – i – 1][j];
                        matrix[ROW – i – 1][j] = matrix[ROW – i – 1][j – 1];
                        matrix[ROW – i – 1][j – 1] = temp;
                    }
                    // Rotate left column
                    for (int j = ROW – i – 1; j > i + 1; j–)
                    {
                        int temp = matrix[j][i];
                        matrix[j][i] = matrix[j – 1][i];
                        matrix[j – 1][i] = temp;
                    }
                }
            }
            // Output final matrix
            for (int i = 0; i < ROW; i++)
            {
                for (int j = 0; j < COLUMN; j++)
                {
                    Console.Write(“{0} “, matrix[i][j]);
                }
                Console.WriteLine(“”);
            }
        }
Happy Programming!!

Leave a Reply

Discover more from AI Infrastructure Architect & Enterprise Solution Architect

Subscribe now to keep reading and get access to the full archive.

Continue reading