1. 题目信息
给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
复制
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. LeetCode 59 解题
类似题目:LeetCode 885. 螺旋矩阵 III
- 创建变量top、bottom表示上下行的区间,left、right表示列的区间
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICMyYTMvw1dvwlMvwlM3VWaWV2Zh1Wa-cmbw5SY3FDb0lTYzFDMvwVN5EDM4kjNtUGall3LcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.png)
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int> > v(n, vector<int>(n,0));
if(n == 0)
return {};
int i, num = 0, total = n*n, top = 0, bottom = n-1, left = 0, right = n-1;
while(num < total)
{
for(i = left; i <= right; ++i)
v[top][i] = ++num;
++top;
for(i = top; i <= bottom; ++i)
v[i][right] = ++num;
--right;
for(i = right; i >= left; --i)
v[bottom][i] = ++num;
--bottom;
for(i = bottom; i >= top; --i)
v[i][left] = ++num;
++left;
}
return v;
}
};
复制
3. LeetCode 54. 螺旋矩阵
给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.empty())
return {};
vector<int> ans;
int m = matrix.size(), n = matrix[0].size();
int i, num = 0, total = m*n, top = 0, bottom = m-1, left = 0, right = n-1;
while(num < total)
{
for(i = left; i <= right; ++i)
ans.push_back(matrix[top][i]),num++;
if(num == total)
break;
++top;
for(i = top; i <= bottom; ++i)
ans.push_back(matrix[i][right]),num++;
if(num == total)
break;
--right;
for(i = right; i >= left; --i)
ans.push_back(matrix[bottom][i]),num++;
if(num == total)
break;
--bottom;
for(i = bottom; i >= top; --i)
ans.push_back(matrix[i][left]),num++;
if(num == total)
break;
++left;
}
return ans;
}
};
复制
4.《剑指Offer》面试题29
面试题29. 顺时针打印矩阵
class Solution { //2020.2.22
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix.size()==0 || matrix[0].size()==0)
return {};
int i = 0, k = 0, count = matrix.size()*matrix[0].size();
int left = 0, right = matrix[0].size()-1, up = 0, bottom = matrix.size()-1;
vector<int> ans(count);
while(count)
{
i = left;
while(count && i <= right)
{
ans[k++] = matrix[up][i++];
count--;
}
up++,
i = up;
while(count && i <= bottom)
{
ans[k++] = matrix[i++][right];
count--;
}
right--;
i = right;
while(count && i >= left)
{
ans[k++] = matrix[bottom][i--];
count--;
}
bottom--;
i = bottom;
while(count && i >= up)
{
ans[k++] = matrix[i--][left];
count--;
}
left++;
}
return ans;
}
};
复制