-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRotation of Matrix
53 lines (32 loc) · 1.69 KB
/
Rotation of Matrix
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
Refrence : https://leetcode.com/problems/determine-whether-matrix-can-be-obtained-by-rotation/
Explanation -
suppose we are at index i, j, let us find a relation of this position with it's position in various rotations
i. e
0deg rotation : i, j will point to i, j
90deg rotation : i, j will point to j, n - i - 1
180deg rotation : i, j will point to n - i - 1, n - j - 1
270deg rotation : i, j will point to n - j - 1, i
We denote these rotations by boolean variables, initially we assume all these rotations are valid, so we set them all to true
here c[0] denotes 0deg rotation, c[1] -> 90deg, c[2] -> 180 deg, c[3] -> 270deg
Then, we loop over all elements and check if that particular rotation is valid or not. If not, we turn it to false.
In the end, we simply check if any of the rotations is still possible or not.
This same code can also be used to find out the valid rotation, i,e 0deg / 90deg / 180 deg/ 270 deg by checking the boolean value in c[0], c[1]. c[2], c[3] respectively.
------------------- Very Clever implementation -------------------------------
class Solution {
public:
bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target) {
vector<bool> X(4 , true);// all possible rotations
int n=mat.size();
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(mat[i][j] != target[i][j]) X[0]=false; // 0
if(mat[i][j] != target[n-j-1][i]) X[1]=false; // 180
if(mat[i][j] != target[n-i-1][n-j-1]) X[2]=false; // 90
if(mat[i][j] != target[j][n-i-1]) X[3]=false; // 270
}
}
return X[0] or X[1] or X[2] or X[3];
}
};