螺旋矩阵 II
2017-04-16 11:08
288 查看
描述
给你一个数n生成一个包含1-n^2的螺旋形矩阵
样例
n = 3
矩阵为:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思考
上下左右都有边界,按照顺序 (向右,向下,向左,向上) 一个轮回,边界不断缩小,所以设置了四个变量表示边界,数字递增直到填满
代码
给你一个数n生成一个包含1-n^2的螺旋形矩阵
样例
n = 3
矩阵为:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思考
上下左右都有边界,按照顺序 (向右,向下,向左,向上) 一个轮回,边界不断缩小,所以设置了四个变量表示边界,数字递增直到填满
代码
// By Lentitude class 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; } };
相关文章推荐
- 螺旋矩阵 II
- lintcode-螺旋矩阵 II
- LeetCode------54. Spiral Matrix(螺旋二维矩阵)-----59. Spiral Matrix II(n的螺旋矩阵)
- Lintcode 螺旋矩阵 II
- [C++]LeetCode: 111 Spiral Matrix II (螺旋写入矩阵)
- LintCode-381.螺旋矩阵 II
- [LeetCode]-Spiral Matrix I&II 螺旋矩阵
- 螺旋矩阵 II -LintCode
- [LeetCode] 59. Spiral Matrix II 螺旋矩阵 II
- [LintCode]381.螺旋矩阵 II
- 1050. 螺旋矩阵(25)
- 蓝桥杯中的螺旋矩阵问题
- noip2014 螺旋矩阵 (模拟)
- 打印螺旋矩阵
- pat乙级真题 1050. 螺旋矩阵(25)
- PAT乙级1050 螺旋矩阵
- PAT乙级 1050. 螺旋矩阵(25)
- 螺旋矩阵(队列)
- 算法:螺旋矩阵 I
- 矩阵螺旋输出