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;
    }
};
相关推荐
smj2302_796826527 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
c++之路9 小时前
C++信号处理
开发语言·c++·信号处理
_深海凉_11 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
故事还在继续吗11 小时前
C++20关键特性
开发语言·c++·c++20
青少儿编程课堂12 小时前
2026青少儿信息素养大赛备赛指南!Python/Scratch/C++备考要点
开发语言·c++·python
踩坑记录12 小时前
leetcode hot100 寻找两个正序数组的中位数 hard 二分查找 双指针
leetcode
旖-旎12 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
AIFarmer12 小时前
【无标题】
开发语言·c++·算法
John_ToDebug13 小时前
WebHostView 与 TabStrip 交互机制深度解析
c++·chrome·windows
南境十里·墨染春水14 小时前
C++笔记 STL——set
开发语言·c++·笔记