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;
    }
};
相关推荐
晚风(●•σ )1 天前
C++语言程序设计——06 字符串
开发语言·c++
晚云与城1 天前
今日分享:C++ -- list 容器
开发语言·c++
阿维的博客日记1 天前
LeetCode 139. 单词拆分 - 动态规划解法详解
leetcode·动态规划·代理模式
兰雪簪轩1 天前
分布式通信平台测试报告
开发语言·网络·c++·网络协议·测试报告
程序员Xu1 天前
【LeetCode热题100道笔记】二叉树的右视图
笔记·算法·leetcode
阿维的博客日记1 天前
LeetCode 48 - 旋转图像算法详解(全网最优雅的Java算法
算法·leetcode
程序员Xu1 天前
【LeetCode热题100道笔记】二叉搜索树中第 K 小的元素
笔记·算法·leetcode
jingfeng5141 天前
C++11可变参数模板、emplace系列接口、包装器
开发语言·c++
Kevinhbr1 天前
CSP-J/S IS COMING
数据结构·c++·算法
蕓晨1 天前
set的插入和pair的用法
c++·算法