Leetcode: 59. Spiral Matrix II 螺旋矩阵II
发布日期:2021-09-14 15:33:17 浏览次数:3 分类:技术文章

本文共 696 字,大约阅读时间需要 2 分钟。

Spiral Matrix II 螺旋矩阵II

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。


输入:

3

输出:

[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]

方法一:模拟螺旋遍历

用left,right,up,down记录

class Solution {
public: vector
> generateMatrix(int n) {
vector
> matrix(n,vector
(n)); int left=0,right=n-1,up=0,down=n-1; int k=1; vector
res; while(true){ for(int i=left;i<=right;i++){ matrix[up][i]=k++; } if(++up>down)break; for(int j=up;j<=down;j++){ matrix[j][right]=k++; } if(--right
=left;i--){ matrix[down][i]=k++; } if(--down
=up;j--){ matrix[j][left]=k++; } if(++left>right) break; } return matrix; }};

转载地址:https://blog.csdn.net/weixin_42490152/article/details/101528526 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Leetcode: 61. Rotate List 旋转链表
下一篇:Leetcode: 54. Spiral Matrix 螺旋矩阵

发表评论

最新留言

路过,博主的博客真漂亮。。
[***.116.15.85]2024年04月12日 15时07分13秒