Lesson 14 of 164
Rotate a Matrix by 90 Degrees
Given an n × n matrix, rotate it by 90 degrees clockwise in place.
LeetCode: 48. Rotate Image
Example
Input: Output:
1 2 3 7 4 1
4 5 6 8 5 2
7 8 9 9 6 3Row i of the input becomes column n - 1 - i of the output: element (i, j) moves to (j, n - 1 - i).
A Java matrix is an int[][]: an array whose elements are row arrays. matrix[i][j] is row i, column j, and Arrays.deepToString prints it.
Brute force: copy into a new matrix
Write every element to its rotated position in a second matrix, then copy it back row by row.
import java.util.Arrays;
public class Main {
static void rotate(int[][] matrix) {
int n = matrix.length;
int[][] rotated = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
rotated[j][n - 1 - i] = matrix[i][j];
}
}
for (int i = 0; i < n; i++) {
matrix[i] = rotated[i];
}
}
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
rotate(m);
System.out.println(Arrays.deepToString(m));
}
}[[7, 4, 1], [8, 5, 2], [9, 6, 3]]Time: O(n²). Space: O(n²) for the copy, which the problem does not allow.
Optimal: transpose, then reverse each row
A clockwise rotation is two simple in-place steps:
- Transpose: swap
(i, j)with(j, i), which moves(i, j)to(j, i). - Reverse each row: moves
(j, i)to(j, n - 1 - i).
1 2 3 transpose 1 4 7 reverse rows 7 4 1
4 5 6 ----------> 2 5 8 -------------> 8 5 2
7 8 9 3 6 9 9 6 3import java.util.Arrays;
public class Main {
static void rotate(int[][] matrix) {
int n = matrix.length;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = tmp;
}
}
for (int[] row : matrix) {
for (int l = 0, r = n - 1; l < r; l++, r--) {
int tmp = row[l];
row[l] = row[r];
row[r] = tmp;
}
}
}
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
rotate(m);
System.out.println(Arrays.deepToString(m));
int[][] m2 = {{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}};
rotate(m2);
System.out.println(Arrays.deepToString(m2));
}
}[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
[[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]Time: O(n²). Space: O(1).
The transpose loop starts j at i + 1, so each pair is swapped once. Starting j at 0 would swap every pair twice and restore the original matrix.
Edge cases
- Counter-clockwise: transpose, then reverse the order of the rows (swap row
iwith rown - 1 - i) instead of reversing each row. - 180 degrees: reverse the rows and reverse each row.
1 × 1or empty: nothing changes.
