Practice › Arrays
Rotate Matrix 90 Degrees
Medium · Arrays · Asked at Amazon, Microsoft, Google, Adobe
Rotate an n × n matrix by 90 degrees clockwise.
Input
First line: n. Next n lines: n integers each.
Output
The rotated matrix: n lines of n space-separated integers.
Constraints
- 1 ≤ n ≤ 100
In place: transpose, then reverse every row.
Example 1
Input
3 1 2 3 4 5 6 7 8 9
Output
7 4 1 8 5 2 9 6 3
Example 2
Input
1 7
Output
7
Hints
- After a clockwise rotation, the first column read bottom-to-top becomes the first row.
- In place: transpose the matrix (swap m[i][j] with m[j][i]), then reverse every row.
Approach
Transposing turns rows into columns, and reversing each row then mirrors left↔right. Together that's a 90° clockwise rotation, done in place. Check it on the sample: the transpose of [[1,2,3],[4,5,6],[7,8,9]] is [[1,4,7],[2,5,8],[3,6,9]], and reversing each row gives [[7,4,1],[8,5,2],[9,6,3]].
Complexity: O(n²) time · O(1) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<vector<long long>> m(n, vector<long long>(n));
for (auto &row : m)
for (auto &x : row) cin >> x;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) swap(m[i][j], m[j][i]);
for (auto &row : m) reverse(row.begin(), row.end());
for (auto &row : m)
for (int j = 0; j < n; j++) cout << row[j] << (j + 1 < n ? " " : "\n");
return 0;
}Python solution
import sys
data = sys.stdin.read().split()
n = int(data[0])
m = [data[1 + i * n : 1 + (i + 1) * n] for i in range(n)]
# zip(*m) transposes; reversing m first turns that into a clockwise rotation
for row in zip(*m[::-1]):
print(*row)Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[][] m = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) m[i][j] = sc.nextLong();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
long t = m[i][j]; m[i][j] = m[j][i]; m[j][i] = t;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = n - 1; j >= 0; j--) sb.append(m[i][j]).append(j > 0 ? " " : "\n");
}
System.out.print(sb);
}
}Solve Rotate Matrix 90 Degrees online · All practice problems