leetCode59. 螺旋矩阵 II

leetCode59. 螺旋矩阵 II

题目思路:见我的这篇博客

代码

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        // n * n的矩阵的初始化
        vector<vector<int>> res(n, vector<int> (n));

        // 方向数组
        int dx[] = {0, 1, 0, -1};
        int dy[] = {1, 0, -1, 0};

        for(int i = 1, x = 0, y = 0, d = 0; i <= n * n; i++){ // 从1开始进行填写,填写到n*n
            res[x][y] = i;
            int x1 = x + dx[d];
            int y1 = y + dy[d];
            if(x1 >= n || x1 < 0 || y1 < 0 || y1 >= n || res[x1][y1]){
                d = (d + 1) % 4;
                x1 = x + dx[d];
                y1 = y + dy[d];
            }

            x = x1, y = y1;
        }

        return res;
    }
};

相关推荐

  1. LeetCode59 螺旋矩阵 II

    2024-04-28 03:54:03       34 阅读
  2. leetCode59. 螺旋矩阵 II

    2024-04-28 03:54:03       15 阅读
  3. 59. 螺旋矩阵 II

    2024-04-28 03:54:03       43 阅读
  4. Golang leetcode59 螺旋矩阵

    2024-04-28 03:54:03       35 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-28 03:54:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-28 03:54:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-28 03:54:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-28 03:54:03       20 阅读

热门阅读

  1. LeetCode 287 寻找重复数字

    2024-04-28 03:54:03       13 阅读
  2. 提示工程的艺术:释放ChatGPT的潜力

    2024-04-28 03:54:03       15 阅读
  3. Pytorch:Attention理解和代码实现

    2024-04-28 03:54:03       15 阅读
  4. Linux 内核深入理解 - 绪论

    2024-04-28 03:54:03       13 阅读
  5. day04--react中批量传递props

    2024-04-28 03:54:03       17 阅读
  6. 随手记:vue2 filters this指向undefined

    2024-04-28 03:54:03       13 阅读
  7. Qt——代码崩溃 free() invalid pointer

    2024-04-28 03:54:03       15 阅读
  8. Nacos

    Nacos

    2024-04-28 03:54:03      12 阅读
  9. ruoyi-cloud-plus的bom

    2024-04-28 03:54:03       12 阅读
  10. 【软考】面向对象设计

    2024-04-28 03:54:03       12 阅读