-
Notifications
You must be signed in to change notification settings - Fork 2
/
rotate_array_by_90degree_anticlockwise.java
84 lines (69 loc) · 2.09 KB
/
rotate_array_by_90degree_anticlockwise.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// Java program to rotate a matrix by 90 degrees
import java.io.*;
class GFG
{
// An Inplace function to rotate a N x N matrix
// by 90 degrees in anti-clockwise direction
static void rotateMatrix(int N, int mat[][])
{
// Consider all squares one by one
for (int x = 0; x < N / 2; x++)
{
// Consider elements in group of 4 in
// current square
for (int y = x; y < N-x-1; y++)
{
// store current cell in temp variable
int temp = mat[x][y];
// move values from right to top
mat[x][y] = mat[y][N-1-x];
// move values from bottom to right
mat[y][N-1-x] = mat[N-1-x][N-1-y];
// move values from left to bottom
mat[N-1-x][N-1-y] = mat[N-1-y][x];
// assign temp to left
mat[N-1-y][x] = temp;
}
}
}
// Function to print the matrix
static void displayMatrix(int N, int mat[][])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
System.out.print(" " + mat[i][j]);
System.out.print("\n");
}
System.out.print("\n");
}
/* Driver program to test above functions */
public static void main (String[] args)
{
int N = 4;
// Test Case 1
int mat[][] =
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}
};
// Tese Case 2
/* int mat[][] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
*/
// Tese Case 3
/*int mat[][] = {
{1, 2},
{4, 5}
};*/
// displayMatrix(mat);
rotateMatrix(N,mat);
// Print rotated matrix
displayMatrix(N,mat);
}
}