解题思路和代码:
#include <iostream>
#include <vector>
using namespace std;
void rotate(vector<vector<int>>& matrix)
{
int size = matrix.size();
if(size == 0) return;
auto arr = matrix;
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
{
arr[i][j] = matrix[size-j-1][i];
}
}
matrix = arr;
}
void rotate_other(vector<vector<int>>& matrix)
{
int n = matrix.size();
if(n == 0) { return; }
int r = (n>>1)-1;
int c = (n-1)>>1;
for(int i = r; i >= 0; --i)
{
for(int j = c; j >= 0; --j)
{
swap(matrix[i][j], matrix[j][n-i-1]);
swap(matrix[i][j], matrix[n-i-1][n-j-1]);
swap(matrix[i][j], matrix[n-j-1][i]);
}
}
}
void rotate_leetcode(vector<vector<int>> &matrix)
{
int n = matrix.size();
for (int i = 0; i < n / 2; ++i) {
for (int j = 0; j < (n + 1) / 2; ++j) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - j - 1][i];
matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];
matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];
matrix[j][n - i - 1] = temp;
}
}
}
void print(vector<vector<int>> matrix)
{
int size = matrix.size();
for(int i = 0; i < size; i++)
{
cout << "[";
for(int j = 0; j < size - 1; j++)
{
cout << matrix[i][j] << ",";
}
cout << matrix[i][size-1] << "]\n";
}
}
int main()
{
vector<vector<int>> matrix = {
{1,2,3},
{4,5,6},
{7,8,9}
};
cout << "原数组:\n";
print(matrix);
cout << "旋转后:\n";
rotate(matrix);
print(matrix);
return 0;
}
|