Rotate Matrix 90 Degrees Clockwise in C: In-Place Algorithm

A matrix rotated clockwise for in-place array practice.
A matrix rotated clockwise for in-place array practice.

Problem Statement

Given an N x N 2D integer matrix, rotate the matrix by 90 degrees clockwise in-place (without allocating an auxiliary second matrix) and print the rotated grid.

Real-World Systems Context

Image rotation in graphical user interfaces, matrix transpositions in neural network tensor layers, and digital signal transforms all rely on in-place 2D array manipulations.

In-Place Rotation Algorithm:

  1. Transpose the matrix: Swap matrix[i][j] with matrix[j][i] for all i < j.
  2. Reverse each row: Reverse elements from column 0 to column N - 1 for every row horizontally.

Complexity & Editorial

Deep Mathematical Intuition: The 2-Step Decomposition

A 90-degree clockwise rotation maps an element from coordinates (row, col) to (col, N - 1 - row).

Rather than executing complicated 4-element cyclical swaps, we decompose the transformation into two orthogonal operations:

  1. Transpose across Main Diagonal:
    matrix[i][j] <-> matrix[j][i]
    This transforms rows into columns. The inner loop must begin at j = i + 1 to ensure cells are swapped exactly once.

  2. Horizontal Reflection:
    Reversing each row maps column j to N - 1 - j:
    matrix[i][j] <-> matrix[i][N - 1 - j]
    This completes the clockwise rotation.

Hardware Cache Friendliness

In C, 2D arrays are laid out in Row-Major order. Reversing row elements accesses adjacent memory addresses, maximizing CPU hardware cache line efficiency.

Starter Code

#include <stdio.h>

#define MAX_N 20

// Function to rotate an N x N matrix 90 degrees clockwise in-place
void rotate_matrix(int n, int matrix[MAX_N][MAX_N]) {
    // TODO: Step 1 - Transpose matrix (swap matrix[i][j] with matrix[j][i] for i < j)

    // TODO: Step 2 - Reverse each row (swap matrix[i][j] with matrix[i][n - 1 - j])
}

int main(void) {
    int n;
    if (scanf("%d", &n) != 1 || n <= 0 || n > MAX_N) {
        return 1;
    }

    int matrix[MAX_N][MAX_N];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    rotate_matrix(n, matrix);

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            printf("%d%s", matrix[i][j], (j == n - 1) ? "" : " ");
        }
        printf("\n");
    }

    return 0;
}

Frequently Asked Questions

How do you rotate a matrix 180 degrees in-place?

Reverse every row horizontally, then reverse the entire matrix vertically (or vice versa).

Why does transposing across the secondary diagonal produce a different rotation?

Transposing across the anti-diagonal followed by horizontal reflection produces a counter-clockwise rotation.

Related exercises