[Leetcode] Spiral Matrix II
2016-12-29 09:05
357 查看
描述
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 ] ]
返回一个螺旋输出是 1,2,3,... 的二维数组。
分析
这道题是Spiral Matrix 的变形,但其实比原题要简单,因为已经知道了二维数组的行和列都是 n ,因此我们只需要按照螺旋顺序,依次在二维数组中填充相应的数字就可以了。具体的螺旋顺序的遍历请看 这里 。代码
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<int> tmp(n, 0);
vector<vector<int>> res(n, tmp);
int row = -1, col = -1, run = 0;
for (int i = 1; i <= n * n;) {
for (row++, col++; col < n - run; col++) res[row][col] = i++;
for (row++, col--; row < n - run; row++) res[row][col] = i++;
for (col--, row--; col >= run; col--) res[row][col] = i++;
for (row--, col++; row > run; row--) res[row][col] = i++;
run++;
}
return res;
}
};
相关问题
Spiral Matrix
相关文章推荐
- leetcode — spiral-matrix-ii
- LeetCode-59-Spiral Matrix II(C语言实现)
- Spiral Matrix II(leetcode)
- Leetcode Spiral Matrix II
- Leetcode: Spiral Matrix II
- leetcode-Spiral Matrix II
- LeetCode54/59 Spiral Matrix I/II
- Leetcode 59. Spiral Matrix II
- LeetCode: Spiral Matrix II
- [Leetcode] Spiral Matrix II
- [leetcode] 59.Spiral Matrix II
- LeetCode - Spiral Matrix I && II - Frequent
- LeetCode 59 Spiral Matrix II
- leetcode 81: Spiral Matrix II
- LeetCode——Spiral Matrix II
- LeetCode-59-Spiral Matrix II(Array)-Medium
- 【LeetCode-面试算法经典-Java实现】【059-Spiral Matrix II(螺旋矩阵II)】
- [leetCode] Spiral Matrix II
- LeetCode Spiral Matrix II
- LeetCode Spiral Matrix II 带打印程序