Leetcode 题组 15(螺旋矩阵)

54. 螺旋矩阵

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int left = 0, right = matrix[0].size()-1, top = 0, bottom = matrix.size()-1;
        vector<int> ans;
        while(left<right&&top<bottom){
            for (int i = left; i < right; ++i) ans.push_back(matrix[top][i]);
            for (int i = top; i < bottom; ++i) ans.push_back(matrix[i][right]);
            for (int i = right; i > left; --i) ans.push_back(matrix[bottom][i]);
            for (int i = bottom; i > top; --i) ans.push_back(matrix[i][left]);
            ++left, --right, ++top, --bottom;
        }
        // 中间只有一个元素
        if (left == right && top == bottom){
            ans.push_back(matrix[top][left]);
            return ans;
        }
        // 还有一列元素没有被放进去
        // 1 2 3
        // 4 5 6
        // 7 8 9
        // 1 2 3
        while(left==right && top<=bottom){
            ans.push_back(matrix[top++][left]);
        }
        // 还有一行元素没有被放进去
        // 1 2 3 4
        // 5 6 7 8
        // 9 0 1 2
        while(top==bottom && left<=right){
            ans.push_back(matrix[top][left++]);
        }
        return ans;
    }
};

 59. 螺旋矩阵 II

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

 

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> ans(n, vector<int>(n, 0));
        int left = 0, right = n - 1, top = 0, bottom = n - 1;
        int num = 1;
        while(left < right){
            for (int i = left; i < right; ++i) ans[top][i] = num++;
            for (int i = top; i < bottom; ++i) ans[i][right] = num++;
            for (int i = right; i > left; --i) ans[bottom][i] = num++;
            for (int i = bottom; i > top; --i) ans[i][left] = num++;
            ++left, --right, ++top, --bottom;
        }
        // 判断中间是否有元素
        if (n%2)
            ans[top][left] = num;
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值