• + 0 comments

    C#

    static void matrixRotation(List<List<int>> matrix, int r)
    {
        int rowsC = matrix.Count;
        int colsC = matrix[0].Count;
    
    
        int rm = 0;
        int rM = rowsC - 1;
    
        int cm = 0;
        int cM = colsC - 1;
    
        int length = (cM - cm + 1) * 2 + (rM - rm + 1) * 2 - 4;
       
        int[] a = new int[length];
    
        // Check if there is something to shift
        while (cm < cM && rm < rM)
        {
            int shifts = r % length;
    
            // Fill array from matrix part given by min/max row/column
            for (int i = cm; i <= cM; i++)
            {
                a[i - cm] = matrix[rm][i];
                a[cM - cm + rM - rm + i - cm] = matrix[rM][cM - i + cm];
            }
    
            for (int j = rm + 1; j <= rM - 1; j++)
            {
                a[cM - cm + j - (rm + 1) + 1] = matrix[j][cM];
                a[cM - cm + rM - rm + cM - cm + j - rm] = matrix[rM - 1 + rm + 1 - j][cm];
            }
    
            // Shift array
            for (int i = 0; i < length / 2; i++)
            {
                (a[i], a[length - 1 - i]) = (a[length - 1 - i], a[i]);
            }
    
            for (int i = 0; i < (length - shifts) / 2; i++)
            {
                (a[i], a[length - shifts - 1 - i]) = (a[length - shifts - 1 - i], a[i]);
            }
    
            for (int i = 0; i < shifts / 2; i++)
            {
                (a[length - shifts + i], a[length - 1 - i]) = (a[length - 1 - i], a[length - shifts + i]);
            }
    
            // Update matrix part given by min/max row/column from shifted array
            for (int i = cm; i <= cM; i++)
            {
                matrix[rm][i] = a[i - cm];
                matrix[rM][cM - i + cm] = a[cM - cm + rM - rm + i - cm];
            }
    
            for (int j = rm + 1; j <= rM - 1; j++)
            {
                matrix[j][cM] = a[cM - cm + j - (rm + 1) + 1];
                matrix[rM - 1 + rm + 1 - j][cm] = a[cM - cm + rM - rm + cM - cm + j - rm];
            }
    
            // Switch matrix part given by min/max row/column to the next level
            rm += 1;
            rM -= 1;
            cm += 1;
            cM -= 1;
    
            length -= 8;
        }
    
        foreach (var t in matrix)
        {
            foreach (var t1 in t) Console.Write($"{t1} ");
            Console.WriteLine();
        }
    }