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;
    }
};
相关推荐
黑不溜秋的1 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
Dream it possible!4 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
夏末秋也凉4 小时前
力扣-回溯-46 全排列
数据结构·算法·leetcode
南宫生4 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
柠石榴4 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
Leuanghing4 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
qy发大财4 小时前
加油站(力扣134)
算法·leetcode·职场和发展
王老师青少年编程4 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛
qy发大财4 小时前
柠檬水找零(力扣860)
算法·leetcode·职场和发展
澄澈天空5 小时前
C++ MFC添加RichEditControl控件后,程序启动失败
c++·mfc