题目描述:
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
AC C++ Solution:
按顺时针顺序填充
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ret( n, vector<int>(n) );
int k = 1, i = 0; //k为装填的数字
while(k <= n * n) {
int j = i;
//for steps
while( j < n - i)
ret[i][j++] = k++; //1. horizonal, left to right
j = i + 1;
while( j < n - i)
ret[j++][n-i-1] = k++; //2. vertical, top to bottom
j = n - i - 2;
while( j > i)
ret[n-i-1][j--] = k++; //3. horizonal, right to left
j = n - i - 1;
while(j > i)
ret[j--][i] = k++; //4. vectical, bottom to top
i++; //next loop
}
return ret;
}
};