您的位置:首页 > 其它

[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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: