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;
    }
};
相关推荐
earthzhang20212 小时前
【1028】字符菱形
c语言·开发语言·数据结构·c++·算法·青少年编程
AA陈超4 小时前
虚幻引擎5 GAS开发俯视角RPG游戏 P05-08 UI 部件数据表
c++·游戏·ue5·游戏引擎·虚幻
纵有疾風起5 小时前
C++——类和对象(3)
开发语言·c++·经验分享·开源
承渊政道6 小时前
动态内存管理
c语言·c++·经验分享·c#·visual studio
孤独得猿6 小时前
聊天室项目开发——etcd的安装和使用
linux·服务器·c++·etcd
new coder7 小时前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
无敌最俊朗@7 小时前
数组-力扣hot56-合并区间
数据结构·算法·leetcode
哼?~8 小时前
C++11标准 上 (万字解析)
开发语言·c++
码农多耕地呗8 小时前
力扣94.二叉树的中序遍历(递归and迭代法)(java)
数据结构·算法·leetcode
给大佬递杯卡布奇诺8 小时前
FFmpeg 基本API avformat_alloc_context 函数内部调用流程分析
c++·ffmpeg·音视频