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;
    }
};
相关推荐
程序员编程指南35 分钟前
Qt 与 WebService 交互开发
c语言·开发语言·c++·qt·交互
溟洵42 分钟前
Qt 窗口 工具栏QToolBar、状态栏StatusBar
开发语言·前端·数据库·c++·后端·qt
铭哥的编程日记1 小时前
《C++ list 完全指南:list的模拟实现》
c++
程序员编程指南1 小时前
Qt 远程过程调用(RPC)实现方案
c语言·c++·qt·rpc·系统架构
十间fish3 小时前
STL温故知新
c++
西红柿煎蛋3 小时前
C++/const
c++
技术卷3 小时前
详解力扣高频SQL50题之610. 判断三角形【简单】
sql·leetcode·oracle
西红柿煎蛋3 小时前
Virtual析构函数
c++
淮北4944 小时前
STL学习(四、队列和堆栈)
开发语言·c++·学习
落羽的落羽4 小时前
【C++】论如何封装红黑树模拟实现set和map
数据结构·c++·学习