Rotate Matrix 90 Degrees
Rotate a square matrix 90 degrees clockwise.
Sample input
[[1,2,3],[4,5,6],[7,8,9]]
Sample output
7 4 1
8 5 2
9 6 3
Solution
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
n = len(matrix)
for i in range(n):
row = [matrix[n - 1 - j][i] for j in range(n)]
print(" ".join(map(str, row)))
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const n = matrix.length;
for (let i = 0; i < n; i++) {
const row = [];
for (let j = 0; j < n; j++) {
row.push(matrix[n - 1 - j][i]);
}
console.log(row.join(" "));
}
public class Main {
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int n = matrix.length;
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < n; j++) {
sb.append(matrix[n - 1 - j][i]);
if (j < n - 1) sb.append(" ");
}
System.out.println(sb.toString());
}
}
}
fun main() {
val matrix = arrayOf(
intArrayOf(1, 2, 3),
intArrayOf(4, 5, 6),
intArrayOf(7, 8, 9)
)
val n = matrix.size
for (i in 0 until n) {
val row = StringBuilder()
for (j in 0 until n) {
row.append(matrix[n - 1 - j][i])
if (j < n - 1) row.append(" ")
}
println(row.toString())
}
}
let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let n = matrix.count
for i in 0..<n {
var row = [String]()
for j in 0..<n {
row.append(String(matrix[n - 1 - j][i]))
}
print(row.joined(separator: " "))
}
void main() {
List<List<int>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
int n = matrix.length;
for (int i = 0; i < n; i++) {
List<int> row = [];
for (int j = 0; j < n; j++) {
row.add(matrix[n - 1 - j][i]);
}
print(row.join(' '));
}
}
#include <iostream>
using namespace std;
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int n = 3;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << matrix[n - 1 - j][i];
if (j < n - 1) cout << " ";
}
cout << endl;
}
return 0;
}
#include <stdio.h>
int main() {
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int n = 3;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d", matrix[n - 1 - j][i]);
if (j < n - 1) printf(" ");
}
printf("\n");
}
return 0;
}