当前位置:   article > 正文

LeetCode59. 螺旋矩阵 II(C++)

LeetCode59. 螺旋矩阵 II(C++)

LeetCode59. 螺旋矩阵 II

题目链接

https://leetcode.cn/problems/spiral-matrix-ii/
在这里插入图片描述

代码

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n, vector<int>(n, 0));
        int startx = 0;
        int starty = 0;
        int i= 0, j = 0;
        int mid = n / 2, loop = n / 2, offset = 1, count = 1;

        while(loop--){
            i = startx;
            j = starty;
            for(j = startx; j < n - offset; j++){
                res[startx][j] = count++;
            }
            for(i = starty; i < n - offset; i++){
                res[i][j] = count++;
            }
            for(; j > startx; j--){
                res[i][j] = count++;
            }
            for(; i >starty; i--){
                res[i][j] = count++;
            }
            startx++;
            starty++;
            offset++;
        } 
        if(n % 2){
            res[mid][mid] = count;
        }
        return res;


    }
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/164739
推荐阅读
相关标签
  

闽ICP备14008679号