旋转90度
寻找原始坐标和旋转后坐标的映射规律,尝试把矩阵进行反转、镜像对称等操作
顺时针旋转90度
- 将 n x n 矩阵 matrix 按照主对角线对称
- 将每一行reverse
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
// 沿主对角线镜像对称二维矩阵
for(int i=0;i<n;i++){
for(int j=i;j<n;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// 然后反转二维矩阵的每一行
for(vector<int>&row: matrix){
reverse(row.begin(),row.end());
}
}
};
逆时针旋转90度
- 将 n x n 矩阵 matrix 按照副对角线对称
- 将每一行reverse
// 将二维矩阵原地逆时针旋转 90 度
void rotate2(vector<vector<int>>& matrix) {
int n = matrix.size();
// 沿副对角线镜像对称二维矩阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[n - j - 1][n - i - 1];
matrix[n - j - 1][n - i - 1] = temp;
}
}
// 然后反转二维矩阵的每一行
for (auto& row : matrix) { // Use & to modify the row.
reverse(row.begin(), row.end());
}
}
螺旋矩阵
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
// m行n列
int m=matrix.size(),n=matrix[0].size();
int upper_bound=0,lower_bound=m-1,left_bound=0,right_bound=n-1;
vector<int> res;
while (res.size() < m * n) {
if (upper_bound <= lower_bound) {
// 在顶部从左向右遍历
for (int j = left_bound; j <= right_bound; j++) {
res.push_back(matrix[upper_bound][j]);
}
// 上边界下移
upper_bound++;
}
if (left_bound <= right_bound) {
// 在右侧从上向下遍历
for (int i = upper_bound; i <= lower_bound; i++) {
res.push_back(matrix[i][right_bound]);
}
// 右边界左移
right_bound--;
}
if (upper_bound <= lower_bound) {
// 在底部从右向左遍历
for (int j = right_bound; j >= left_bound; j--) {
res.push_back(matrix[lower_bound][j]);
}
// 下边界上移
lower_bound--;
}
if (left_bound <= right_bound) {
// 在左侧从下向上遍历
for (int i = lower_bound; i >= upper_bound; i--) {
res.push_back(matrix[i][left_bound]);
}
// 左边界右移
left_bound++;
}
}
return res;
}
};