Simple C solution, recursive and in-place


  • 0
    M

    We are recursively transforming the matrix from the periphery.

    void rr(int** m, int r, int n)
    {
        int j;
    
        /* End recursion */
        if (r >= n)
            return;
    
        /* Rotate all the elements in the row */
        for (j = r; j < n; ++j)
        {
            swap_int(m[r] + j, m[j] + n);
            swap_int(m[r] + j, m[n] + n - (j - r));
            swap_int(m[r] + j, m[n - (j - r)] + r);
        }
    
        /* Advance to the inner n-1 x n-1 sub-matrix */
        return rr(m, r + 1, n - 1);
    }
    
    void rotate(int** matrix, int matrixRowSize, int matrixColSize)
    {
        /*Maintain Sanity */
        if (!matrix || !matrixRowSize || (matrixRowSize != matrixColSize))
            return matrix;
        return rr(matrix, 0, matrixColSize - 1);
    }
    

Log in to reply
 

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