Open
Description
public:
vector<vector<int>> generateMatrix(int n) {
// Be careful on the boundary conditions
int start = 0, end = n - 1;
int x = 1;
// 2D vector should be initialized correctly!!!
vector<vector<int>> mat(n, vector<int>(n));
while (start<=end) {
int i = start, j = start;
while (j < end) {
mat[i][j++] = x++;
}
while (i < end) {
mat[i++][j] = x++;
}
while (j > start) {
mat[i][j--] = x++;
}
while (i > start) {
mat[i--][j] = x++;
}
start++;
end--;
}
// if n is odd
if (n % 2) {
mat[n / 2][n / 2] = x;
}
return mat;
}
};
Metadata
Metadata
Assignees
Labels
No labels