螺旋矩阵 II
来源:互联网 发布:东坡软件下载 编辑:程序博客网 时间:2024/06/08 02:40
描述
给你一个数n生成一个包含1-n^2的螺旋形矩阵
样例
n = 3
矩阵为:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思考
- 上下左右都有边界,按照顺序 (向右,向下,向左,向上) 一个轮回,边界不断缩小,所以设置了四个变量表示边界,数字递增直到填满
代码
// By Lentitudeclass Solution {public: /** * @param n an integer * @return a square matrix */ vector<vector<int>> generateMatrix(int n) { // Write your code here // 初始化 vector 二维动态数组 vector<vector<int> > vec(n); for (int i = 0; i != n; ++i){ vec[i].resize(n); } int value = 1; int x = 0; int x_left = 0; // 起始的 X 索引位置 int x_right = n - 1; // 结束的 X 索引位置 int y = 0; int y_top = 0; // 起始的 Y 索引位置 int y_bottom = n - 1; // 结束的 Y 索引位置 while (value <= n*n){ // 000 -> 123 while (x <= x_right && vec[y_top][x] == 0){ vec[y_top][x++] = value++; } // if (vec[(n + 1)/2 - 1] == n*n){ // return vec; // } y_top++; y = y_top; /** * 3 -> 3 * 0 4 * 0 5 */ while (y <= y_bottom && vec[y][x_right] == 0){ vec[y++][x_right] = value++; } x_right--; x = x_right; /** * 005 -> 765 */ while (x >= x_left && vec[y_bottom][x] == 0){ vec[y_bottom][x--] = value++; } y_bottom--; y = y_bottom; /** * 0 -> 9 * 0 8 * 7 7 */ while (y >= y_top && vec[y][x_left] == 0){ vec[y--][x_left] = value++; } x_left++; x = x_left; } return vec; }};
0 0
- lintcode-螺旋矩阵 II
- 螺旋矩阵II
- 螺旋矩阵 II
- Lintcode 螺旋矩阵 II
- lintcode --螺旋矩阵II
- 螺旋矩阵 II -LintCode
- [LintCode]381.螺旋矩阵 II
- Spiral Matrix II 螺旋矩阵II
- [LintCode] 螺旋矩阵II Spiral Matrix II
- [LeetCode]-Spiral Matrix I&II 螺旋矩阵
- LeetCode Spiral Matrix II (生成螺旋矩阵)
- leetcode 59. Spiral Matrix II (螺旋矩阵)
- 381.Spiral Matrix II-螺旋矩阵 II(中等题)
- LeetCode------54. Spiral Matrix(螺旋二维矩阵)-----59. Spiral Matrix II(n的螺旋矩阵)
- 每日算法之四十一:Spiral Matrix II (螺旋矩阵)
- LeetCode | Spiral Matrix II(螺旋矩阵填充数据)
- LeetCode OJ 之 Spiral Matrix II (螺旋矩阵 - 二)
- [C++]LeetCode: 111 Spiral Matrix II (螺旋写入矩阵)
- CodeForces
- C#中DllImport用法汇总
- hdu2852 KiKi's K-Number 线段树
- LeetCode#91. Decode Ways
- Week Training: 452 Minimum Number of Arrows to Burst Balloons
- 螺旋矩阵 II
- 客户端显示2008连接上却实2005数据库
- prophet:时间序列预测模型原理
- Shell 编程入门
- simple_factory
- Leetcode: Set Matrix Zeroes
- 支付宝安卓端调用说明
- qt中筛选出最小的未被占用的串口号
- WebSphere MQ使用