C++ | Leetcode C++题解之第59题螺旋矩阵II

题目:

题解:

cpp 复制代码
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        int num = 1;
        vector<vector<int>> matrix(n, vector<int>(n));
        int left = 0, right = n - 1, top = 0, bottom = n - 1;
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                matrix[top][column] = num;
                num++;
            }
            for (int row = top + 1; row <= bottom; row++) {
                matrix[row][right] = num;
                num++;
            }
            if (left < right && top < bottom) {
                for (int column = right - 1; column > left; column--) {
                    matrix[bottom][column] = num;
                    num++;
                }
                for (int row = bottom; row > top; row--) {
                    matrix[row][left] = num;
                    num++;
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return matrix;
    }
};
相关推荐
joker D88823 分钟前
【C++】深入理解 unordered 容器、布隆过滤器与分布式一致性哈希
c++·分布式·哈希算法
野曙1 小时前
快速选择算法:优化大数据中的 Top-K 问题
大数据·数据结构·c++·算法·第k小·第k大
休息一下接着来2 小时前
C++ 条件变量与线程通知机制:std::condition_variable
开发语言·c++·算法
爱学习的小邓同学2 小时前
C++ --- new与delete
c++
努力学习的小廉2 小时前
【C++】 —— 笔试刷题day_29
开发语言·c++·算法
小羊在奋斗2 小时前
【LeetCode 热题 100】搜索插入位置 / 搜索旋转排序数组 / 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
六bring个六3 小时前
文件系统交互实现
开发语言·c++·qt·交互
小山菌3 小时前
mac中加载C++动态库文件
开发语言·c++·macos
疯狂学习GIS3 小时前
Windows配置VS Code详细流程
c++·学术工作效率
__BMGT()3 小时前
C++ QT图片查看器
前端·c++·qt