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;}
};