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;
    }
};
相关推荐
千金裘换酒3 小时前
LeetCode 移动零元素 快慢指针
算法·leetcode·职场和发展
byxdaz4 小时前
C++内存序
c++
优雅的潮叭4 小时前
c++ 学习笔记之 malloc
c++·笔记·学习
漫随流水4 小时前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
苦藤新鸡6 小时前
8.最长的无重复字符的子串
c++·力扣
千金裘换酒6 小时前
LeetCode反转链表
算法·leetcode·链表
꧁Q༒ོγ꧂7 小时前
C++ 入门完全指南(四)--函数与模块化编程
开发语言·c++
汉克老师7 小时前
GESP2025年12月认证C++八级真题与解析(判断题8-10)
c++·快速排序··lcs·gesp八级·gesp8级
qq_433554547 小时前
C++ manacher(求解回文串问题)
开发语言·c++·算法
圣保罗的大教堂8 小时前
leetcode 1161. 最大层内元素和 中等
leetcode