思路
旋转分为两步:1、将矩阵转置,2、翻转当前行
#include <vector>
using namespace std;
class Solution {
public:
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
void swapMatrix(vector<int>& line)
{
int n = line.size();
for (int i = 0; i < n / 2; i++)
{
swap(line[i], line[n - i - 1]);
}
}
/*先装置,然后翻转每行数字*/
void rotate(vector<vector<int>>& matrix) {
auto matSize = matrix.size();
for (int i = 0; i < matSize; i++)
{
for (int j = i + 1; j < matSize; j++)
{
swap(matrix[i][j], matrix[j][i]);
//std::swap(matrix[i][j], matrix[j][i]);
}
swapMatrix(matrix[i]);
//reverse(matrix[i].begin(), matrix[i].end());
}
}
};
int main(int argc, char* argv[])
{
vector<vector<int>> matrix = { {1 , 2, 3 ,4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16} };
vector<int> line = { 1 , 2, 3 ,4 };
Solution().swapMatrix(line);
Solution().rotate(matrix);
return 0;
}
网友评论