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;
    }
};
相关推荐
一拳一个呆瓜2 小时前
【STL】iostream 编程:检测提取操作产生的错误
c++·stl
稚南城才子,乌衣巷风流2 小时前
判断素数与拓展应用
c++
众少成多积小致巨2 小时前
C++ 规范参考(下)
c++
c238562 小时前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法
txzrxz3 小时前
最短路问题——Dijkstra 算法
数据结构·c++·算法·最短路·优先队列
noipp4 小时前
推荐题目:洛谷 P6231 [JSOI2013] 公交系统
c语言·数据结构·c++·算法·游戏·洛谷·luogu
c238564 小时前
C/C++每日一练6
c语言·c++·算法
念恒123064 小时前
网络基础
linux·网络·c++
mct1235 小时前
c++ iconv 字符utf-8转换gb2312失败
开发语言·c++
ziguo11225 小时前
Windows API 文件操作超级指南——从入门到内核
c++·windows·visualstudio