[leetcode] Spiral Matrix II
来源:互联网 发布:美国软件清理手机 编辑:程序博客网 时间:2024/06/03 15:27
From : https://leetcode.com/problems/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
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
class Solution {public: vector<vector<int>> generateMatrix(int n) { if(n < 0 ) n=(~n)+1; vector<vector<int>> ans(n, vector<int>(n)); int u=0, d=n-1, l=0, r=n-1, v=1, nn=n*n; while(v<=nn) { for(int i=l; i<=r; i++) ans[u][i] = v++; if(v>nn) break; u++; for(int i=u; i<=d; i++) ans[i][r] = v++; if(v>nn) break; r--; for(int i=r; i>=l; i--) ans[d][i] = v++; if(v>nn) break; d--; for(int i=d; i>=u; i--) ans[i][l] = v++; if(v>nn) break; l++; } return ans; }};
public class Solution { public int[][] generateMatrix(int n) { int[][] m = new int[n][n]; int l=0, t=0, r=n-1, b=n-1; int u = 0; while(l<=r && t<=b) { for(int i=l; i<=r; ++i) { m[t][i] = ++u; } ++t; for(int i=t; i<=b; ++i) { m[i][r] = ++u; } --r; for(int i=r; i>=l; --i) { m[b][i] = ++u; } --b; for(int i=b; i>=t; --i) { m[i][l] = ++u; } ++l; } return m; }}
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
- Spiral Matrix II -- LeetCode
- Cookie的使用
- FaceNet--Google的人脸识别
- ITOO之底层关系
- 二叉树题目集合
- 日志分析系统所用知识
- [leetcode] Spiral Matrix II
- 最全最强解析:支付宝钱包系统架构内部剖析(架构图)
- 我写的一个 Qt 显示图片的控件
- 黑马day10 使用PrepareStatement增加&删除&更改
- Shadowsocks上网利器
- 毕业论文题目: 基于Android平台的手机防火墙的设计与实现
- 欢迎使用CSDN-markdown编辑器
- spring 源码解读与设计详解: 7 BeanDefinitionParserDelegate深入解读
- halcon二维测量