59. Spiral Matrix II
Solution (C++):
vector<vector<int>> generateMatrix(int n) {
if (!n) return vector<vector<int>> {};
vector<vector<int>> res(n, vector<int>(n, 0));
vector<vector<int>> direc{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int direc_index = 0, val = 1;
int x = 0, y = -1; //initial position (0, -1)
vector<int> steps{n, n-1};
while (steps[direc_index%2]) {
for (int i = 0; i < steps[direc_index%2]; ++i) {
x += direc[direc_index][0];
y += direc[direc_index][1];
res[x][y] = val++;
}
steps[direc_index%2]--;
direc_index = (direc_index + 1) % 4;
}
return res;
}
性能:
Runtime: 0 ms Memory Usage: 9.1 MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。