Simple C# Solution


  • 0
    P
    public class Solution {
        public void Rotate(int[,] mat) {
                  VerticalInverse(mat);
                DiagonalInverse(mat);
        }
        
        public void DiagonalInverse(int[,] mat) {
                // input:
                //{ 7, 8, 9 }, 
                //{ 4, 5, 6 }, 
                //{ 1, 2, 3 } 
    
                // output: diagonally invert the matrix
                //{ 7, 4, 1 }, 
                //{ 8, 5, 2 }, 
                //{ 9, 6, 3 } 
    
                int rowCount = mat.GetLength(0);
                int columnCount = mat.GetLength(1);
    
                for (int i = 0; i < rowCount; i++)
                {
                    for (int j = i; j < columnCount; j++)
                    {
                        Swap(mat, i, j, j, i);
                    }
                }
            }
    
            /// <summary>
            /// Method to inverse the matrix vertically.
            /// </summary>
            /// <param name="arr"></param>
            void VerticalInverse(int[,] arr)
            {
                // input:
                //{ 1, 2, 3 }, 
                //{ 4, 5, 6 }, 
                //{ 7, 8, 9 } 
    
                // expected outout: Clockwise 90 degree rotation
                //{ 7, 8, 9 }, 
                //{ 4, 5, 6 }, 
                //{ 1, 2, 3 } 
    
                int rowCount = arr.GetLength(0);
                int columnCount = arr.GetLength(1);
    
                for (int i = 0; i < rowCount / 2; i++)
                {
                    for (int j = 0; j < columnCount; j++)
                    {
                        Swap(arr, i, j, rowCount - 1 - i, j);
                    }
                }
            }
    
            /// <summary>
            /// Mathod to swap two given indexes of the matrix
            /// </summary>
            /// <param name="arr">array</param>
            /// <param name="fromRow">row index 1</param>
            /// <param name="fromCol">column index 1</param>
            /// <param name="toRow">row index 2</param>
            /// <param name="toCol">column index 2</param>
            void Swap(int[,] arr, int fromRow, int fromCol, int toRow, int toCol)
            {
                int temp = arr[fromRow, fromCol];
                arr[fromRow, fromCol] = arr[toRow, toCol];
                arr[toRow, toCol] = temp;
            }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.