forked from Ritesh25696/interviewBit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotate Matrix
More file actions
65 lines (54 loc) · 1.58 KB
/
Rotate Matrix
File metadata and controls
65 lines (54 loc) · 1.58 KB
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
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
You need to do this in place.
Note that if you end up using an additional array, you will only receive partial score.
Example:
If the array is
[
[1, 2],
[3, 4]
]
Then the rotated array becomes:
[
[3, 1],
[4, 2]
]
******************************************************************************************
void Solution::rotate(vector<vector<int> > &arr) {
int rows = arr.size();
int col = arr.size();
for (int i = 0; i < rows; i++)
{
for (int j = i + 1; j < col; j++)
{
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < col / 2; j++)
{
int temp = arr[i][j];
arr[i][j] = arr[i][col - 1 - j];
arr[i][col - 1 - j] = temp;
}
}
}
**************************************************************************************************************************************************
class Solution {
public:
void rotate(vector<vector<int> > &matrix) {
int len = matrix.size();
for (int i = 0; i < len / 2; i++) {
for (int j = i; j < len - i - 1; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[len - j - 1][i];
matrix[len - j - 1][i] = matrix[len - i - 1][len - j - 1];
matrix[len - i - 1][len - j - 1] = matrix[j][len - i - 1];
matrix[j][len - i - 1] = tmp;
}
}
}
};