LeetCode:Spiral Matrix II
2016-03-02 15:01
423 查看
Spiral Matrix II
Total Accepted: 48130 TotalSubmissions: 140755 Difficulty: Medium
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 ] ]
Hide Tags
Array
class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> ret(n, vector<int>(n)); int rowStart = 0, rowEnd = n-1; int colStart = 0, colEnd = n-1; int num = 1; while(num <= n*n) { for(int i=colStart;i<=colEnd;i++) // "→" ret[rowStart][i] = num++; rowStart++; for(int i=rowStart;i<=rowEnd;i++) // "↓" ret[i][colEnd] = num++; colEnd--; for(int i=colEnd;i>=colStart;i--) // "←" ret[rowEnd][i] = num++; rowEnd--; for(int i=rowEnd;i>=rowStart;i--) // "↑" ret[i][colStart] = num++; colStart++; } return ret; } };
相关文章推荐
- BIT2014级软件学院程序设计-04合并果子
- Java生成和操作Excel文件
- php7 php-fpm 显示空白页原因一例
- dao 获取表最大排序实现
- iOS SDWebImage使用详解
- cxf+Spring的webservice应用
- LeetCode104: Maximum Depth of Binary Tree
- c++复习1-求三角形面积
- ESLint 使用入门
- CentOS怎样强制卸载PHP以及自定义安装PHP
- Android AccessibilityService 使用详解
- LVM原理及PV、VG、LV、PE、LE关系图
- STM32的选型参考
- long与byte互转中的错误
- 轻量级linux CRUX安装笔记
- oc知识点 类的扩展
- !function(){}()
- FFmpeg avcodec_open2不成功broken ffmpeg default settings detected跟H264的设置有关
- 数据库索引-扫盲
- HSOG: A Novel Local Image Descriptor Based on Histogram of the Second-Order Gradients