# [C++]LeetCode: 110 Spiral Matrix II (螺旋写入矩阵)

2015-01-25

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 ]
]```

Attention：

1. 返回空数组 别忘了括号。

`if(n == 0) return vector>();`

2. 初始化数组

`vector> ret(n, vector(n, 0));`

3. 要记得判断是否达到数字最大&#20540;。每次遍历都需要判断

```if (num <= n^2)
{
//向右遍历添加
for (int j = colBegin; j <= colEnd; j++)
{
ret[rowBegin][j] = num;
num++;
}
}```

AC Code:

```class Solution {
public:
vector > generateMatrix(int n) {
if(n == 0) return vector>();
vector> ret(n, vector(n, 0));

int rowBegin = 0;
int rowEnd = n - 1;
int colBegin = 0;
int colEnd = n - 1;
int num = 1;

while (rowBegin <= rowEnd && colBegin <= colEnd)
{
if (num <= n^2)
{
//向右遍历添加
for (int j = colBegin; j <= colEnd; j++)
{
ret[rowBegin][j] = num;
num++;
}
}
rowBegin++;

if (num <= n^2)
{
//向下遍历添加
for (int i = rowBegin; i <= rowEnd; i++)
{
ret[i][colEnd] = num;
num++;
}
}
colEnd--;

if (num <= n^2)
{
//向左遍历添加
for (int j = colEnd; j >= colBegin; j--)
{
ret[rowEnd][j] = num;
num++;
}
}
rowEnd--;

if (num <= n^2)
{
//向上遍历添加
for (int i = rowEnd; i >= rowBegin; i--)
{
ret[i][colBegin] = num;
num++;
}
}
colBegin++;
}

return ret;
}
};```