Skip to content

Commit 1b200c8

Browse files
author
kwu130
committed
feat(src): add 48-rotate
1 parent cc422e7 commit 1b200c8

1 file changed

Lines changed: 61 additions & 0 deletions

File tree

‎src/48-rotate.cpp‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
//
2+
// Created by 1412 on 2025/10/28.
3+
//
4+
5+
#include <bits/stdc++.h>
6+
7+
using namespace std;
8+
9+
class Solution {
10+
public:
11+
void rotate(vector<vector<int>>& matrix) {
12+
int m = matrix.size();
13+
int n = matrix[0].size();
14+
for (int i = 0; i < m; i++) {
15+
for (int j = i; j < n; j++) {
16+
swap(matrix[i][j], matrix[j][i]); // 转置
17+
}
18+
}
19+
for (int i = 0; i < m; i++) {
20+
for (int j = 0; j < n / 2; j++) {
21+
swap(matrix[i][j], matrix[i][n - j - 1]); // 镜像
22+
}
23+
}
24+
}
25+
};
26+
27+
void test() {
28+
Solution s;
29+
vector<vector<int>> matrix = {
30+
{1, 2, 3},
31+
{4, 5, 6},
32+
{7, 8, 9}
33+
};
34+
vector<vector<int>> expected = {
35+
{7, 4, 1},
36+
{8, 5, 2},
37+
{9, 6, 3}
38+
};
39+
s.rotate(matrix);
40+
assert(matrix == expected);
41+
42+
matrix = {
43+
{ 5, 1, 9, 11},
44+
{ 2, 4, 8, 10},
45+
{13, 3, 6, 7},
46+
{15, 14, 12, 16}
47+
};
48+
expected = {
49+
{15, 13, 2, 5},
50+
{14, 3, 4, 1},
51+
{12, 6, 8, 9},
52+
{16, 7, 10, 11}
53+
};
54+
s.rotate(matrix);
55+
assert(matrix == expected);
56+
}
57+
58+
int main() {
59+
test();
60+
return 0;
61+
}

0 commit comments

Comments
 (0)