Introduction
Question: 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
提示:
解法一
Analysis
和LC54-spiral-matrix非常类似,直接改改之前代码就过了。
Implement
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
| int ifirst, ilast, jfirst, jlast; vector<int> moveI{0, 1, 0, -1}; vector<int> moveJ{1, 0, -1, 0}; void transform(int &i, int &j, int &state) { if (state == 0 && j == jlast) { state = (state + 1) % 4; jlast--; } else if (state == 1 && i == ilast) { state = (state + 1) % 4; ilast--; } else if (state == 2 && j == jfirst) { state = (state + 1) % 4; jfirst++; } else if (state == 3 && i == ifirst) { state = (state + 1) % 4; ifirst++; } i += moveI[state]; j += moveJ[state]; } vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n, vector<int>(n));
ifirst = jfirst = 0; ilast = jlast = n-1; int i = 0, j = 0, state = 0; ifirst++;
for(int t = 1, size = n*n;t <= size;t++) { res[i][j] = t; transform(i, j, state); }
return res; }
|