螺旋矩阵ii spiral-matrix-ii
题目描述
给定一个整数n,将数字1到n^2n
2
按螺旋的顺序填入n×n的矩阵
例如:
给出的n=3,
你应该返回如下矩阵:
[↵ [ 1, 2, 3 ],↵ [ 8, 9, 4 ],↵ [ 7, 6, 5 ]↵]
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =3,
You should return the following matrix:
[↵ [ 1, 2, 3 ],↵ [ 8, 9, 4 ],↵ [ 7, 6, 5 ]↵]↵
示例
输入
2
输出
[[1,2],[4,3]]
解题思路
- 将螺旋矩阵看成一个个同心矩阵,从外往内一层一层地按照顺时针顺序遍历。
- 设定四个边界:left,right,top,bottom,初始分别为0,n - 1,0,n - 1
- 每一个同心矩阵的四个边界范围(从上面那条边开始)分别是left ~ right, top + 1 ~ bottom, right - 1 ~ left, bottom + 1~top - 1
- 每遍历完一个同心矩阵,left++, right- -, top- -, bottom++
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > result(n, vector<int>(n));
if(n < 1) return result;
//四个边界
int left(0), right(n - 1), top(0), bottom(n - 1);
//用于不断累加计数,填入螺旋矩阵
int cnt(1);
while(left <= right && top <= bottom) {
//填充上边界
for(int i = left; i <= right; i ++) {
result[top][i] = cnt ++;
}
//填充右边界
for(int i = top + 1; i <= bottom; i ++) {
result[i][right] = cnt ++;
}
//填充下边界
for(int i = right - 1; i >= left; i --) {
result[bottom][i] = cnt ++;
}
//填充左边界
for(int i = bottom - 1; i >= top + 1; i --) {
result[i][left] = cnt ++;
}
//修改四个边界,继续填充下一层同心矩阵
left ++; right --; top ++; bottom --;
}
return result;
}
};