Skip to content

Commit 4a2a387

Browse files
committed
rotate matrix
1 parent 219278f commit 4a2a387

File tree

2 files changed

+68
-1
lines changed

2 files changed

+68
-1
lines changed

Striver Sheet/Day-2/Rotate Image.cpp

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Rotate Image
3+
============
4+
5+
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
6+
7+
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
8+
9+
Example 1:
10+
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
11+
Output: [[7,4,1],[8,5,2],[9,6,3]]
12+
13+
Example 2:
14+
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
15+
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
16+
17+
Example 3:
18+
Input: matrix = [[1]]
19+
Output: [[1]]
20+
21+
Example 4:
22+
Input: matrix = [[1,2],[3,4]]
23+
Output: [[3,1],[4,2]]
24+
25+
Constraints:
26+
matrix.length == n
27+
matrix[i].length == n
28+
1 <= n <= 20
29+
-1000 <= matrix[i][j] <= 1000
30+
*/
31+
32+
class Solution
33+
{
34+
public:
35+
void rotate(vector<vector<int>> &matrix)
36+
{
37+
int n = matrix.size();
38+
if (!n)
39+
return;
40+
int m = matrix[0].size();
41+
if (!m)
42+
return;
43+
44+
for (int i = 0; i < n; ++i)
45+
{
46+
for (int j = 0; j < i; ++j)
47+
{
48+
int temp = matrix[i][j];
49+
matrix[i][j] = matrix[j][i];
50+
matrix[j][i] = temp;
51+
}
52+
}
53+
54+
for (int i = 0; i < n; ++i)
55+
{
56+
int mi = 0, ma = m - 1;
57+
while (mi < ma)
58+
{
59+
swap(matrix[i][mi], matrix[i][ma]);
60+
mi++;
61+
ma--;
62+
}
63+
}
64+
}
65+
};

Striver Sheet/README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# STRIVER DSA SHEET
22

3+
[Sheet Link](https://docs.google.com/document/d/1JLKCaz4n4YtYdQ1bJF1X46BKbxldedb6N1OMiXh9Dmo/edit?usp=sharing)
4+
35
### Day 1 (Arrays)
46

57
- [Sort an array of 0’s 1’s 2’s without using extra space or sorting algo](https://leetcode.com/problems/sort-colors/) - [Cpp Soultion](./Day-1/Sort%20Colors.cpp)
@@ -16,7 +18,7 @@
1618
- [Next Permutation](https://leetcode.com/problems/next-permutation/) - [Cpp Soultion](./Day-2/Next%20Permutation.cpp)
1719
- [Count Inversions in an array](https://www.geeksforgeeks.org/counting-inversions/) - [Cpp Soultion](./Day-2/Count%20Inversions.cpp)
1820
- [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) - [Cpp Soultion](./Day-2/Best%20Time%20to%20Buy%20and%20Sell%20Stock.cpp)
19-
- []() - [Cpp Soultion](./Day-2/.cpp)
21+
- [Rotate Image](https://leetcode.com/problems/rotate-image/) - [Cpp Soultion](./Day-2/Rotate%20Image.cpp)
2022

2123
###
2224

0 commit comments

Comments
 (0)