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;
    }
};
相关推荐
sysu_chenxy1 小时前
二重循环输出二维图形
c++
Navigator_Z1 小时前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2082 小时前
leetcode 64最小路径和
算法·leetcode·职场和发展
Nil2082 小时前
leetcode 72编辑距离
算法·leetcode·职场和发展
划破黑暗的第一缕曙光2 小时前
[C++]:2.类和对象(下)
c++·类和对象·对象·类
Nil2083 小时前
leetcode 136只出现一次的数字
leetcode·哈希算法·散列表
lvwangshu4 小时前
川剧复演 题解
动态规划·题解·技巧·性质题·思维好题
黎相思4 小时前
LRU Cache
c++·缓存
UIU1144 小时前
P1003 [NOIP 2011 提高组] 铺地毯
数据结构·c++·算法
xxwl5855 小时前
区域赛算法模版第四章---数据结构
数据结构·c++·算法