59. 螺旋矩阵 II
给你一个正整数 n
,生成一个包含 1
到 n2
所有元素,且元素按顺时针顺序螺旋排列的 n x n
正方形矩阵 matrix
。
示例 1:
输入:n = 3 输出:[[1,2,3],[8,9,4],[7,6,5]]
示例 2:
输入:n = 1 输出:[[1]]
这是一道模拟题,没有啥需要的算法,但是很考验对代码的掌握程度,稍不留意就会出错。我这里采用左闭右开的方式进行模拟。下面直接看代码就能知道大概的思路了,需要注意的就是边界条件以及n分为奇数偶数的情况。下面是完整的C++代码:
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 off = 1;int loop = n / 2;int i,j;int count = 1;int mid = n / 2;while(loop--){i = startx;j = starty;for(j;j < n - off;j++){res[i][j] = count++;}for(i;i < n - off;i++){res[i][j] = count++;}for( ;j > startx;j--){res[i][j] = count++;}for(;i > startx;i--){res[i][j] = count++;}startx++;starty++;off++;}if(n % 2){res[mid][mid] = count++;}return res;}
};