class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> vec_vec_int(n, vector<int>(n));
int num = 1;
int n2 = n * n;
int left = 0,right = n - 1, top = 0, bottom = n - 1;
while(num <= n2){
for(int j = left; j <= right; j++){
vec_vec_int[top][j] = num++;
}
top++;
for(int j = top; j <= bottom; j++){
vec_vec_int[j][right] = num++;
}
right--;
for(int j = right; j >= left; j--){
vec_vec_int[bottom][j] = num++;
}
bottom--;
for(int j = bottom; j >= top; j--){
vec_vec_int[j][left] = num++;
}
left++;
}
return vec_vec_int;
}
};
Accepted
20/20 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 49.61 % of cpp submissions (6.4 MB)