Skip to content

Commit 8d20bb1

Browse files
Merge pull request #252 from vish-han/patch-6
Rotate a Matrix by 90deg added
2 parents 0a5c8c4 + 3c5b6ca commit 8d20bb1

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//Question : you are given an 2D array , you have to rotate the Matrix bt 90deg and return it;
2+
3+
public class ArrayPermutation {
4+
public static void main(String[] args) {
5+
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
6+
//array before rotation
7+
for (int i = 0; i < array.length; i++) {
8+
for (int j = 0; j < array.length; j++) {
9+
System.out.print(array[i][j] + " ");
10+
}
11+
System.out.println();
12+
}
13+
rotate(array);
14+
System.out.println("===========================================================");
15+
System.out.println("after Rotation");
16+
17+
for (int i = 0; i < array.length; i++) {
18+
for (int j = 0; j < array.length; j++) {
19+
System.out.print(array[i][j] + " ");
20+
}
21+
System.out.println();
22+
}
23+
}
24+
25+
//this functon will rotate the array by 90deg by taking transpose the array and rotate each row
26+
static void rotate(int[][] matrix) {
27+
int n = matrix.length;
28+
for (int i = 0; i < (n + 1) / 2; i++) {
29+
for (int j = 0; j < n / 2; j++) {
30+
int temp = matrix[n - 1 - j][i];
31+
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - j - 1];
32+
matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i];
33+
matrix[j][n - 1 - i] = matrix[i][j];
34+
matrix[i][j] = temp;
35+
}
36+
}
37+
}
38+
39+
}

0 commit comments

Comments
 (0)