给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。
示例:
输入: 3
输出:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
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;
}
};
给定一个包含 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;
}
};
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;
}
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有