C++ | Leetcode C++题解之第59题螺旋矩阵II

题目:

题解:

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. 59. 螺旋矩阵 II

    2024-05-01 17:36:04       63 阅读
  2. LeetCode59 螺旋矩阵 II

    2024-05-01 17:36:04       53 阅读
  3. leetCode59. 螺旋矩阵 II

    2024-05-01 17:36:04       36 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-05-01 17:36:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-05-01 17:36:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-05-01 17:36:04       87 阅读
  4. Python语言-面向对象

    2024-05-01 17:36:04       96 阅读

热门阅读

  1. “IP地址的未来:IPv6的机遇与挑战“

    2024-05-01 17:36:04       34 阅读
  2. CSS背景图像显示方式

    2024-05-01 17:36:04       35 阅读
  3. Element-UI快速入门

    2024-05-01 17:36:04       37 阅读
  4. 以AI技术与街景影像重塑城市研究

    2024-05-01 17:36:04       31 阅读
  5. 前端 判断和获取各种数据类型

    2024-05-01 17:36:04       37 阅读