【LeetCode从零单刷】Spiral Matrix II
来源:互联网 发布:在线打电话软件 编辑:程序博客网 时间:2024/06/07 23:50
题目:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
解答:
重要的是找到循环的规律:每层环都可以由四个部分组成,第一个环每部分长为(n-1),第二个环每部分长为(n-3)…(n-2k)… 如下图所示:
对于奇数与偶数不同的地方在于:奇数螺旋矩阵的最中间仅有一个部分组成,取值为 n;偶数螺旋矩阵的最中间仍然是四个部分。
class Solution {public: vector<vector<int>> generateMatrix(int n) { vector<int> row(n, 0); vector<vector<int>> ans(n, row); if(n <= 0) return ans; int x = 0, y = 0; int num = 0; int a, b, c, d; for(int i=n-1; i>=0; i=i-2) { if(i == 0) ans[x][y] = n*n; else { for(a = 0; a < i; a++) { ans[x][y+a] = ++num; } y = y + i; for(b = 0; b < i; b++) { ans[x+b][y] = ++num; } x = x + i; for(c = 0; c < i; c++) { ans[x][y-c] = ++num; } y = y - i; for(d = 0; d < i; d++) { ans[x-d][y] = ++num; } x = x - i + 1; y = y + 1; } } return ans; }};
0 0
- 【LeetCode从零单刷】Spiral Matrix II
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix II
- LeetCode : Spiral Matrix II
- [LeetCode] Spiral Matrix II
- [LeetCode]Spiral Matrix II
- [leetcode]Spiral Matrix II
- LeetCode-Spiral Matrix II
- [leetcode] Spiral Matrix II
- LeetCode - Spiral Matrix II
- Leetcode: Spiral Matrix II
- 【LeetCode】Spiral Matrix II
- Leetcode Spiral Matrix II
- [LeetCode] Spiral Matrix II
- LeetCode | Spiral Matrix II
- LeetCode Spiral Matrix II
- Leetcode: Spiral Matrix II
- 创建带Apache服务的Centos Docker镜像
- Windows命令启动MySQL“ 发生系统错误 5 ”
- 面向对象四大特征
- object-c中NSString与int和float的相互转换
- java设计模式之抽象工厂模式
- 【LeetCode从零单刷】Spiral Matrix II
- 黑马程序员——网络编程(Socket编程)
- html+css2次学习-----常用知识点总结
- VS2013中安装配置和使用Boost库
- uvaLive 3713
- python学习-文本数据分析1(主题提取+词向量化)
- shell自学笔记2
- hadoop运行到mapreduce.job: Running job后停止运行
- JavaScript高级程序设计之客户端检测之能力检测第9.1讲笔记