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;
    }
};
相关推荐
楼田莉子33 分钟前
C++IO流学习
开发语言·c++·windows·学习·visual studio
轩情吖40 分钟前
Qt常用控件之QComboBox
开发语言·c++·qt·控件·下拉框·qcombobox·桌面级开发
深思慎考1 小时前
LinuxC++——spdlog日志使用入门
linux·数据库·c++
tpoog2 小时前
[C++项目框架库]redis的简单介绍和使用
开发语言·c++·redis
郝学胜-神的一滴3 小时前
深入理解 C++ 中的 `std::bind`:功能、用法与实践
开发语言·c++·算法·软件工程
1白天的黑夜13 小时前
优先级队列(堆)-1046.最后一块砖的重量-力扣(LeetCode)
c++·leetcode·优先级队列
努力学习的小廉3 小时前
我爱学算法之—— 模拟(上)
c++·算法
仰泳的熊猫3 小时前
LeetCode:496. 下一个更大元素 I
数据结构·c++·算法·leetcode
bkspiderx4 小时前
C++设计模式之行为型模式:职责链模式(Chain of Responsibility)
c++·设计模式·责任链模式
勇闯逆流河4 小时前
【C++】AVL详解
开发语言·c++