[Algorithms] LeetCode 59. 螺旋矩阵 II
Categories Algorithms Array
Tags
来源:代码随想录
考察基本功啊,区间统一左闭右开,最后记得处理n为奇数的情况。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> v(n, vector<int>(n));
int index = 1;
int startIndex = 0;
while (startIndex <= n / 2) {
for (int j = startIndex; j < n - startIndex - 1; j++) {
v[startIndex][j] = index;
index++;
}
for (int i = startIndex; i < n - startIndex - 1; i++) {
v[i][n - startIndex - 1] = index;
index++;
}
for (int j = n - startIndex - 1; j > startIndex; j--) {
v[n - startIndex - 1][j] = index;
index++;
}
for (int i = n - startIndex - 1; i > startIndex; i--) {
v[i][startIndex] = index;
index++;
}
startIndex++;
}
if (n % 2) {
v[n / 2][n / 2] = n * n;
}
return v;
}
};
Page views: Loading... · Visitors: Loading...
Except where otherwise noted, original content on this site is dedicated to the public domain under CC0 1.0.
Powered by Hexo & Theme mdsuper
沪ICP备2026040813号