Given a positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.
n?
1 <= n <= 20 for such problems, but we should confirm.n = 1?Assuming the problem follows the typical constraints and output format:
Given n = 3, the output should be:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
matrix with dimensions n x n and initialize with zeros or empty values.top, bottom, left, right), initialized as 0, n-1, 0, and n-1 respectively.current_num <= n*n):
#include <vector>
std::vector<std::vector<int>> generateMatrix(int n) {
std::vector<std::vector<int>> matrix(n, std::vector<int>(n, 0));
int current_num = 1;
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (current_num <= n * n) {
// Traverse from left to right along the top boundary.
for (int i = left; i <= right; ++i) {
matrix[top][i] = current_num++;
}
top++;
// Traverse from top to bottom along the right boundary.
for (int i = top; i <= bottom; ++i) {
matrix[i][right] = current_num++;
}
right--;
// Traverse from right to left along the bottom boundary.
for (int i = right; i >= left; --i) {
matrix[bottom][i] = current_num++;
}
bottom--;
// Traverse from bottom to top along the left boundary.
for (int i = bottom; i >= top; --i) {
matrix[i][left] = current_num++;
}
left++;
}
return matrix;
}
n x n matrix.This approach efficiently fills the matrix in a spiral order while maintaining ease of implementation and understanding.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?