二维数组题

旋转90度

寻找原始坐标和旋转后坐标的映射规律,尝试把矩阵进行反转、镜像对称等操作

顺时针旋转90度

  1. 将 n x n 矩阵 matrix 按照主对角线对称
  2. 将每一行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度

  1. 将 n x n 矩阵 matrix 按照副对角线对称
  2. 将每一行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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值