LeetCode 59. Spiral Matrix II
59. Spiral Matrix II
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 ]
]
题目大意:给一个n,输出一个n*n的数组,并且按照螺旋的方式填充入数字1~n*n。
分析:按照一个个矩阵的边框输入:x为矩阵的上界,n为矩阵的上界,每次输出这个围成的矩阵的第一行——最后一列——最后一行——第一列,然后将x自增1,m自减1~
注意:为了避免重复输出,当x和n相等的时候,就输入一次第一行和最后一列就可以,不用重复输入最后一行和第一列~
class Solution { public:vector<vector<int>> generateMatrix(int n) {vector<vector<int>> result(n, vector<int>(n));n = n - 1;int num = 1;for (int x = 0; x <= n; x++, n--) {for (int j = x; j <= n; j++)result[x][j] = num++;for (int i = x + 1; i <= n - 1; i++)result[i][n] = num++;for (int j = n; j >= x && x != n; j--)result[n][j] = num++;for (int i = n - 1; i >= x + 1 && x != n; i--)result[i][x] = num++;}return result;} };
LeetCode 59. Spiral Matrix II相关推荐
- LeetCode 59 Spiral Matrix II(螺旋矩阵II)(Array)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/5214 ...
- 59. Spiral Matrix II
/** 59. Spiral Matrix II * 12.5 by Mingyang* 注意,这里我们说的Matrix就是正方形,不再是长方形了,所以我们会用* 更简单的方法,就是直接上下左右分别加 ...
- LeetCode 58 Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For ...
- 59. Spiral Matrix II ***
description: 螺旋型填充矩阵 Note: Example: Example:Input: 3 Output: [[ 1, 2, 3 ],[ 8, 9, 4 ],[ 7, 6, 5 ] ] ...
- 代码随想录算法训练营第二天 | LeetCode 977.有序数组的平方、LeetCode 209.长度最小的子数组、LeetCode 59.螺旋矩阵II
LeetCode 977.有序数组的平方 双指针法:数组其实是有序的, 只不过负数平方之后可能成为最大数了.那么数组平方的最大值就在数组的两端,不是最左边就是最右边,不可能是中间.此时可以考虑双指针法 ...
- LeetCode Spiral Matrix II (生成螺旋矩阵)
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. F ...
- C#LeetCode刷题之#59-螺旋矩阵 II(Spiral Matrix II)
目录 问题 示例 分析 问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3678 访问. 给定一个正整数 n,生成一 ...
- LeetCode 59. 螺旋矩阵 II LeetCode 54. 螺旋矩阵
文章目录 1. 题目信息 2. LeetCode 59 解题 3. LeetCode 54. 螺旋矩阵 4.<剑指Offer>面试题29 1. 题目信息 给定一个正整数 n,生成一个包含 ...
- LeetCode 54. Spiral Matrix
54. Spiral Matrix Given a matrix of m x n elements (m rows, n columns), return all elements of the m ...
最新文章
- 如何使用Leangoo管理Sprint Backlog
- mount查看linux分区大小,Linux磁盘管理----分区格式化挂载fdisk、mkfs、mount
- Scala 函数传名调用(call-by-name)
- JDK 8中方便的新地图默认方法
- 日常问题——初始化Hive仓库报错com.google.common.base.Preconditions.checkArgument
- Visual Studio 2017 15.6发布
- Hadoop技术在商业智能BI中的应用
- 阳振坤:电动汽车与分布式数据库的共同命运
- 在输入文本框中获取值
- 单片机的各种存储的含义和区别
- 数据库学习笔记5-隔离级别 Repeatable Read
- 进销存excel_Excel进销存管理套表,自动库存显示应收应付,全函数快捷轻松
- 模糊c-均值聚类算法(FCM)
- 有了这些视频画面裁剪软件,视频裁剪再也不是什么难题了
- 解决ubuntu无法连接网络问题
- R语言作图——Lollipop chart(棒棒糖图)
- 【暑假】[实用数据结构]UVAlive 4670 Dominating Patterns
- php扩展-ioncube组件的安装方法_如何安装ioncube扩展
- 手机用户对手机游戏的偏好调查
- 学习 Python 之 Pandas库