Start learning free

LESSON 49 OF 314 · MATRIX

Rotate Image in C#: Transpose, Then Reverse Each Row

Practice O(n^2) Read the full explanation

You get a square grid matrix of integers, with n rows and n columns.

Rotate it a quarter turn clockwise, like turning a photo onto its right side.

matrix is an array of rows. Each row is an array of integers. Row 0 is the top row. Column 0 is the leftmost column.

Work in place. Change the numbers inside matrix itself, and don't fill a new grid.

Your function returns nothing. Each example's output shows matrix after the function runs.

 

Example 1:

Input: matrix = [
  [4, 9, 2],
  [3, 5, 7],
  [8, 1, 6]
]
Output: [
  [8, 3, 4],
  [1, 5, 9],
  [6, 7, 2]
]
Explanation: The left column, read from the bottom up, is now the top row.
The top row is now the right column.
The 5 in the center stays where it is.

Example 2:

Input: matrix = [
  [-3, 8],
  [8, 0]
]
Output: [
  [8, -3],
  [0, 8]
]
Explanation: Each number moves to the next corner clockwise:
-3 goes to the top right,
the top-right 8 goes to the bottom right,
0 goes to the bottom left,
the bottom-left 8 goes to the top left.

Example 3:

Input: matrix = [
  [7]
]
Output: [
  [7]
]
Explanation: A single number has nowhere to move.

 

Constraints:

  • n is from 1 to 500.
  • Each value is an integer from -1000 to 1000.
  • Negative values and repeats are allowed.

Note:

Your algorithm should run in O(n2) time and use O(1) extra space: it only moves numbers around inside matrix.

STEP 1 OF 6
    Ctrl + Enter to check

    C# · MATRIX

    Rotate Image in C#, explained

    Problem overview

    The method Rotate receives a square matrix as an int[][]: an array of n rows, each an array of n integers. It must turn the matrix a quarter turn clockwise, in place, and return nothing. The caller sees the rotated numbers in the same matrix object. The method should run in O(n²) time and use O(1) extra space.

    For {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} the result is {{7, 4, 1}, {8, 5, 2}, {9, 6, 3}}. The left column read from the bottom up, 7, 4, 1, becomes the top row, and the top row 1, 2, 3 becomes the right column.

    Approach: two simple flips

    Building a second matrix and copying each value to its rotated position is easy, but it needs O(n²) extra space, which the lesson rules out. Moving each value straight to its final cell in place is possible (it means rotating four cells at a time), but the index arithmetic is easy to get wrong.

    A cleaner route uses two reflections that are each easy to do in place:

    1. Transpose the matrix: reflect it over its main diagonal, so the value at row i, column j moves to row j, column i. Rows become columns.
    2. Reverse every row.

    Together they make a clockwise quarter turn. For the 3x3 example, the transpose gives {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}}. The first row, 1, 4, 7, was the first column read top to bottom. A clockwise turn needs that column read from the bottom up, so reversing the row gives 7, 4, 1, the first row of the answer. Every other row works the same way.

    Step by step

    1. Store the size. matrix.Length is the number of rows, and since the matrix is square, it is also the number of columns. Call it n.
    2. Loop over the rows with i from 0 to n - 1 for the transpose.
    3. Loop over the columns to the right of the diagonal, with j starting at i + 1. Each pair of mirrored cells is visited once. If j started at 0, every pair would be swapped twice, and the second swap would undo the first. Cells on the diagonal map to themselves, so they need no swap.
    4. Swap matrix[i][j] and matrix[j][i] with a tuple assignment, so no temporary variable is needed.
    5. Loop over the rows again and reverse each one with Array.Reverse, which works on the row array where it is.

    The solution in C#

    class Solution {
        public void Rotate(int[][] matrix) {
            int n = matrix.Length;
            for (int i = 0; i < n; i++) {
                for (int j = i + 1; j < n; j++) {
                    (matrix[i][j], matrix[j][i]) = (matrix[j][i], matrix[i][j]);
                }
            }
            for (int i = 0; i < n; i++) {
                Array.Reverse(matrix[i]);
            }
        }
    }
    

    C# details worth knowing:

    • Tuple swap. The right-hand side (matrix[j][i], matrix[i][j]) builds a tuple holding both current values before anything is assigned. The left-hand side then assigns them to the two cells in the other order. This is the idiomatic swap in modern C#.
    • Jagged array. int[][] is an array of arrays, indexed matrix[i][j]. That is different from the rectangular int[,], which is indexed matrix[i, j] and has no row arrays to reverse.
    • In-place reversal. Array.Reverse(array) reverses the array it receives and returns nothing. Because matrix[i] is a reference to the actual row, the matrix itself changes. In a standalone file Array needs using System;.
    • Rows are references. Swapping single cells between rows works because each row is its own array. The caller's matrix is changed, which is what the lesson wants.

    Complexity

    Time: O(n²). The transpose visits about half of the n² cells, and the reversal touches every cell once. Both are proportional to the number of cells.

    Space: O(1). The tuple swap and the reversal need only a constant number of temporary values, and no second matrix is created.

    Edge cases and common mistakes

    • 1x1 matrix. The inner loop never runs and reversing a one-element row changes nothing, so {{7}} stays {{7}}.
    • 2x2 matrix. {{1, 2}, {3, 4}} becomes {{3, 1}, {4, 2}}.
    • Even and odd sizes. The same code handles both; the center cell of an odd matrix is on the diagonal and stays put.
    • Starting j at 0. Every pair is swapped twice and the matrix returns to its original form after the first loop.
    • Reversing each row before the transpose. The same two steps in the other order turn the matrix counterclockwise: {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} would end as {{3, 6, 9}, {2, 5, 8}, {1, 4, 7}}. Transpose first for a clockwise turn.
    • Returning a new matrix. The method is void and the caller reads the same array, so assigning matrix = newMatrix inside the method changes only a local variable and the caller sees nothing.

    Testing

    • {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} becomes {{7, 4, 1}, {8, 5, 2}, {9, 6, 3}}.
    • {{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}} becomes {{15, 13, 2, 5}, {14, 3, 4, 1}, {12, 6, 8, 9}, {16, 7, 10, 11}}.
    • {{1, 2}, {3, 4}} becomes {{3, 1}, {4, 2}}.
    • {{7}} stays {{7}}.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free