Rotate a matrix by 90 degree without using any extra space
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.
Examples:
Input:
1 2 3
4 5 6
7 8 9
Output:
3 6 9
2 5 8
1 4 7
Rotated the input matrix by
90 degrees in anti-clockwise direction.
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Rotated the input matrix by
90 degrees in anti-clockwise direction.
// for 90deg counter clockwise rotation
class Solution {
static void reverseColumns(int arr[][]) {
for (int i = 0; i < arr[0].length; i++) {
for (int j = 0, k = arr[0].length - 1; j < k; j++, k--) {
int temp = arr[j][i];
arr[j][i] = arr[k][i];
arr[k][i] = temp;
}
}
}
// Function for do transpose of matrix
static void transpose(int arr[][]) {
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr[0].length; j++) {
int temp = arr[j][i];
arr[j][i] = arr[i][j];
arr[i][j] = temp;
}
}
}
static void rotate90(int arr[][]) {
transpose(arr);
reverseColumns(arr);
}
}
// for 90deg clockwise
class Solution {
public void rotate(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = i; j < matrix.length; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0, k = matrix.length - 1; j < k; j++, k--) {
int temp = matrix[i][j];
matrix[i][j] = matrix[i][k];
matrix[i][k] = temp;
}
}
}
}
Last updated