一、题目
给你一个正整数 n
,生成一个包含 1
到 所有元素,且元素按顺时针顺序螺旋排列的 正方形矩阵 matrix
。
【示例】输入n=3时,得到如下矩阵
[[1,2,3],[8,9,4],[7,6,5]]
二、思路及要点
主要依赖四个方向的循环实现题目要求(两行两列),需要注意临界时的条件判断。
通过四个变量控制:
start_line, end_line, start_col, end_col
如果n为奇数,则矩阵正中央的数循环中是填不进去的,需要特殊判断
if (n % 2 == 1)
{
a[(n - 1) / 2][(n - 1) / 2] = cnt;
}
三、代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> a(n,vector<int>(n,0));
int start_line = 0, end_line = n - 1;
int start_col = 0, end_col = n - 1;
int cnt = 1;
while (cnt < (n * n))
{
for (int j = start_col; j <= end_col; j++)
{
a[start_line][j] = cnt;
cnt++;
}
start_line++;
for (int i = start_line; i <= end_line; i++)
{
a[i][end_col] = cnt;
cnt++;
}
end_col--;
for (int j = end_col; j >= start_col; j--)
{
a[end_line][j] = cnt;
cnt++;
}
end_line--;
for (int i = end_line; i >= start_line; i--)
{
a[i][start_col] = cnt;
cnt++;
}
start_col++;
}
if (n % 2 == 1)
{
a[(n - 1) / 2][(n - 1) / 2] = cnt;
}
return a;
}
};