描述
给你一个数n生成一个包含1-n^2的螺旋形矩阵
样例
n = 3
矩阵为:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思考
- 上下左右都有边界,按照顺序 (向右,向下,向左,向上) 一个轮回,边界不断缩小,所以设置了四个变量表示边界,数字递增直到填满
代码
// By Lentitude
class Solution {
public:
/**
* @param n an integer
* @return a square matrix
*/
vector<vector<int>> generateMatrix(int n) {
// Write your code here
// 初始化 vector 二维动态数组
vector<vector<int> > vec(n);
for (int i = 0; i != n; ++i){
vec[i].resize(n);
}
int value = 1;
int x = 0;
int x_left = 0; // 起始的 X 索引位置
int x_right = n - 1; // 结束的 X 索引位置
int y = 0;
int y_top = 0; // 起始的 Y 索引位置
int y_bottom = n - 1; // 结束的 Y 索引位置
while (value <= n*n){
// 000 -> 123
while (x <= x_right && vec[y_top][x] == 0){
vec[y_top][x++] = value++;
}
// if (vec[(n + 1)/2 - 1] == n*n){
// return vec;
// }
y_top++;
y = y_top;
/**
* 3 -> 3
* 0 4
* 0 5
*/
while (y <= y_bottom && vec[y][x_right] == 0){
vec[y++][x_right] = value++;
}
x_right--;
x = x_right;
/**
* 005 -> 765
*/
while (x >= x_left && vec[y_bottom][x] == 0){
vec[y_bottom][x--] = value++;
}
y_bottom--;
y = y_bottom;
/**
* 0 -> 9
* 0 8
* 7 7
*/
while (y >= y_top && vec[y][x_left] == 0){
vec[y--][x_left] = value++;
}
x_left++;
x = x_left;
}
return vec;
}
};