文章作者:Tyan
博客:noahsnail.com | CSDN |
1. Description
2. Solution
class Solution {
public:
vector> generateMatrix(int n) {
int total = n * n;
vector> matrix;
for(int i = 0; i < n; i++) {
vector row(n, 0);
matrix.push_back(row);
}
for(int i = 0, j = 0, count = 0; count < total; i++, j++) {
// top
for(int k = j; k < n - j; k++) {
matrix[i][k] = ++count;
}
// right
for(int k = i + 1; k < n - i; k++) {
matrix[k][n - 1 - j] = ++count;
}
// bottom
for(int k = n - 2 - j; k >= j; k--) {
matrix[n - 1 - i][k] = ++count;
}
// left
for(int k = n - 2 - i; k > i; k--) {
matrix[k][j] = ++count;
}
}
return matrix;
}
};
Reference
- https://leetcode.com/problems/spiral-matrix-ii/description/