螺旋矩阵 II
题目
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
- 输入:n = 3
- 输出:[[1,2,3],[8,9,4],[7,6,5]]
代码
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 37 38 39 40 41 42 43 44 45 46 47
| class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n, vector<int>(n, 0)); int startx = 0, starty = 0; int loop = n / 2; int mid = n / 2; int count = 1; int offset = 1; int i,j; while (loop --) { i = startx; j = starty;
for (j; j < n - offset; j++) { res[i][j] = count++; } for (i; i < n - offset; i++) { res[i][j] = count++; } for (; j > starty; j--) { res[i][j] = count++; } for (; i > startx; i--) { res[i][j] = count++; }
startx++; starty++;
offset += 1; }
if (n % 2) { res[mid][mid] = count; } return res; } };
|
Ref
代码随想录